In short, the problem I'm having is two-fold; my request is not posting its data to the server, and AsyncTask seems to be performing multiple times per single execution. I'll elaborate...
I'm developing an application using web-services I wrote in PHP. In my application code, I have events that trigger my request handler new HTTPRequestHandler().execute("myurl.php","POST");
The problem is almost certainly between these lines of code:
try {
json.put("test", uri[1]);
Log.d("Testing", uri[1]);
StringEntity httpPost = new StringEntity(json.toString(), HTTP.UTF_8);
httpPost.setContentType("application/json");
post.setEntity(httpPost);
httpclient.execute(post);
result = "Success";
} catch (JSONException e) {
//some Error logging(e);
}
It quite simply does not seem to attach any URL parameters to the request, and so no data is being sent to my server. Here is my code for the RequestHandler
public class HTTPRequestHandler extends AsyncTask{
final String key = "?key=verylongkey";
@Override
public String doInBackground(String... uri) {
String verb = uri[1];
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
InputStream inputStream = null;
StringBuilder stringbuilder = new StringBuilder();
String result = null;
//begin GET request
if(verb.equals("GET")){
//functional code for get; prints desired results
}
//begin POST request
}else if(verb.equals("POST")){
HttpPost post = new HttpPost(uri[0]+key);
JSONObject json = new JSONObject();
try {
json.put("test", uri[1]);
Log.d("Testing", uri[1]);
StringEntity httpPost = new StringEntity(json.toString(), HTTP.UTF_8);
httpPost.setContentType("application/json");
post.setEntity(httpPost);
httpclient.execute(post);
result = "Success";
} catch (JSONException e) {
Log.e("Testing", "Execution failure: exception: ", e);
} catch (UnsupportedEncodingException e){
Log.e("Testing", "Execution failure: exception: ", e);
} catch (ClientProtocolException e) {
Log.e("Testing", "Execution failure: exception: ", e);
} catch (IOException e) {
Log.e("Testing", "Execution failure: exception: ", e);
}
//endregion
}else{
result = "no valid method specified";
}
return result;
}
@Override
public void onPostExecute(String result){
super.onPostExecute(result);
JSONObject jsonObject;
try {
jsonObject = new JSONObject(result);
List<String> stuff =new ArrayList<String>();
JSONArray cast = jsonObject.getJSONArray("Results");
for (int i=0;i<cast.length();i++){
JSONObject json_data = cast.getJSONObject(i);
Log.d("Testing", "Array["+i+"]"+json_data.getString("mykey"));
}
}catch(JSONException e) {
Log.e("Testing", "Execution failure: exception: ", e);
}
}
}
I'm in the process of writing code which logs some information about the POST request, but I'll get to that once the post is actually working. My PHP looks like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('default_charset', 'UTF-8');
//non-empty credential strings
$server = '';
$user = '';
$pass = '';
$dbname = '';
if ($_GET['key'] == "HwLpn88NZcb8LaCYTKaLFRpUZuGRfP92HB8DJYQvdPQEeKZWBNDkprnfzmzjP8cMsUJCpvXb") {
$con = mysqli_connect($server, $user, $pass, $dbname);
if (!$con) {
die("Connection failure: " . $con -> connect_error);
} else {
if (!empty($_GET["test"])) {
$value = $_GET["test"];
echo $value;
$insert = mysqli_query($con, "INSERT INTO table (column) VALUES ('$value')");
if($insert){
echo "inserted";
}
} else {
//assume functional non-post request code which prints desired data
}
}
$con -> close();
}
?>
and hitting this url in my browser with the url parameter &test=somevalue
I can see in my database that the data is actually being posted since $_GET["test"]
is not empty;
Most of the code above is from tutorials and other posts I've seen. I can't believe there's not an easier way to do this here in 2015, so if you're looking at this thinking "Why not just use this library which makes your request 5 lines of code?" please do enlighten me.
UPDATE
Ok, so now I'm trying $_POST["mykey"]
in my PHP, and I've updated my Java to look like this:
JSONObject json = new JSONObject();
json.put("test","65481");
url = new URL (uri[0]+key);
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
// as per the suggested comment
printout = new DataOutputStream(urlConn.getOutputStream());
byte[] data=json.toString().getBytes("UTF-8");
printout.write(data);
printout.flush();
printout.close();
result="Post Success";
But I still get no post. What is a good way, using this form of code as suggested by a commenter, to get the resulting PHP response?