I am going to implement the client-to-Server module which request is sent from Android devices to php . When it comes to the implementation , I have no clue why the server side cannot receive the json sent from Android device . As for the server, the database insert module is OK but cannot catch the json values . Would you please tell me what is wrong with the client side ?
The below is my code
Client side Android
public String postData(String argument , String url) {
String result="";
// Create a new HttpClient and Post Header
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000 * 20;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000 * 20;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpConnectionParams.setSocketBufferSize(httpParameters, 8*1024);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
//Log.d("url" , url);
HttpPost httppost = new HttpPost(url);
try {
System.out.println("Response:"+ "start execute");
JSONObject json = new JSONObject();
json.put("userid","loka");
json.put("password","yoor");
json.put("email","johnsmith@example.com");
//Log.d("test" , jsonString);
httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
httppost.setHeader( "Content-Type", "application/json" );
//httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
//If php json response required
if(status==200){
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
System.out.println("result: "+ result);
}else{
System.out.println("2");
result = String.valueOf(status);
HttpEntity getResponseEntity = response.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
result = slurp(httpResponseStream , 8192);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return e.getMessage();
} catch (ConnectTimeoutException e){
e.printStackTrace();
return e.getMessage();
}catch (IOException e) {
e.printStackTrace();
return e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Server side php
<?php
header('Content-type: application/json');
ini_set('display_errors','On');
require_once 'lib_mysql/insert.php';
$json = file_get_contents('php://input');
$result =insertUser($json);
if($result) {
echo "success";
}
else{
echo "fail";
}
?>
include_once("connection.php");
function insertUser($jsonString){
$usern = $jsonString->userid; //Undefined Variables
$pass = $jsonString->password; //Undefined Variables
$email = $jsonString->email; //Undefined Variables
$conn = getDBConn();
$data = false;