Reputation: 607
I have tried looking at several links but I cannot seem to get it right. I am trying to send a JSON object from my android application which contains 'username' and 'password'. But I am not sure if this data is actually been sent to the web-service. I am not too sure if I got the code right for reading JSON object in the php script.
JSONObject jsonObject = new JSONObject();
String userID = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
jsonObject.put("password", password);
JSONArray array = new JSONArray();
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
userID = EntityUtils.toString(httpResponse.getEntity());
Log.i("Read from server", userID);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
Here is the beginning of the PHP script.
<?php
include('dbconnect.php');
$tablename = 'users';
//username and password sent from android
$username=$_REQUEST['username'];
$password=$_REQUEST['password'];
.....
?>
Can you tell me what I'm doing wrong here please? I cannot seem to figure out.
Thank you
Upvotes: 0
Views: 1501
Reputation: 4874
You should add a list of NameValuePairs
to your HttpPost
object, so you know the keys you can use to retrieve the data in your PHP script. See the example code snippets below.
The Java:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
The PHP:
$username = $_POST['username']
$password = $_POST['password']
Upvotes: 1