0

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?

Csteele5
  • 1,262
  • 1
  • 18
  • 36
  • 1
    Im pretty sure you have to read the response from the server for the request to actually happen. – JamMaster Nov 13 '15 at 20:06
  • 1
    There are librarys for this! One I love is Retrofit! http://square.github.io/retrofit/ – riggaroo Nov 13 '15 at 20:09
  • 2
    It's hard to tell what you're trying to do here. Do you understand the difference between GET and POST? Using POST will not add parameters to the url. In order to get POST parameters use `_POST` instead of `_GET`. Last, it looks like your code is trying to send JSON to the PHP, is that what you intended? Take a look at my blog post, it might help: http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html – Daniel Nugent Nov 13 '15 at 20:12
  • I accidentally left out a line of `json.put("key","value");` but yes, I am intending to use JSON to append my parameters. I'm looking at it now, and I see you're using URLobject. Should I be using this instead of HttpClient? I'm told HttpClient is deprecated. Let me try to implement your code and I'll post back here with the results. If you all are willing to post these suggestions as data, I'll be happy to upvote and in the event of success, accept. – Csteele5 Nov 13 '15 at 20:19
  • 1
    @Csteele5 Take a look at this for sending JSON: http://stackoverflow.com/questions/13911993/sending-a-json-http-post-request-from-android And here for receiving JSON in the PHP: http://stackoverflow.com/questions/18866571/receive-json-post-with-php – Daniel Nugent Nov 13 '15 at 20:36
  • Thanks! But I must admit, I'm still somewhat confused. I've made some changes, please see my post @DanielNugent – Csteele5 Nov 13 '15 at 21:56
  • 1
    @Csteele5 If you're sending JSON, you can't use _GET or _POST, you need to use `json_decode(file_get_contents('php://input'), true);` Take a look at this answer: http://stackoverflow.com/a/18867369/4409409 – Daniel Nugent Nov 13 '15 at 22:43
  • 1
    @DanielNugent I'm sure you've heard this before, but you're the reason why StackOverflow is such a wonderful place. I got it working :D Thanks so much for all your help! – Csteele5 Nov 13 '15 at 23:15

1 Answers1

0

My communication between the sending Java code and the receiving PHP code was a little mismatched. Because I'm sending JSON, I have to actually say so and json_decode the posted data. It's also important to note that although a connection may have been opened, until I read the data, the POST will not be completed.

PHP

if (file_get_contents('php://input') != false) {

    $data = json_decode(file_get_contents('php://input'), true);
    $value = $data["test"];
    echo $value;

    $insert = mysqli_query($con, "INSERT INTO mytable (mycolumn) VALUES ('$value')");

    if($insert){
        echo "Success";
}

JAVA

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.connect();

printout = new DataOutputStream(urlConn.getOutputStream());
byte[] data=json.toString().getBytes("UTF-8");
printout.write(data);

input = new DataInputStream(urlConn.getInputStream());
StringBuffer inputLine = new StringBuffer();
String tmp;

//it seems until input.readLine() is called, the POST would not execute
while ((tmp = input.readLine()) != null){
    inputLine.append(tmp);
    Log.d("Testing","Contents:"+tmp);
}

printout.flush();
printout.close();

result="Post Success";
Csteele5
  • 1,262
  • 1
  • 18
  • 36