Android HttpClient response

I am trying to send json data to php script from my android app using HttpClient and get a response.

Android Code

private void sendPurchase(String SKU) throws IOException{       
    Log.e("sendPurchase","Inside sendPurchase");
    final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
    int pur_user = prefs.getInt("C_user", Integer.MIN_VALUE);
    InputStream inputStream = null;
    String result = "";
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost("http://www.*.com/includes/purchase.php");            
    JSONObject json = new JSONObject();            
    try {
        json.put("PUR_sku", SKU);
        json.put("PUR_user", pur_user);
    } catch (JSONException e) { Log.e("SendPurchase","Problem with Json Object"); }     
    Log.i("JSONObject", json.toString());
    StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
    httpPost.setEntity(se);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");          
    HttpResponse httpResponse = httpclient.execute(httpPost);
    inputStream = httpResponse.getEntity().getContent();
    if(inputStream != null){ result = convertInputStreamToString(inputStream); }
    else{result = "Did not work!"; }
    Log.e("RESULT",result);     
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line; 
    inputStream.close();
    return result; 
}

      

And PHP script

<? 
$auth=0;
require('./connexion.php');
$data = file_get_contents('php://input');
//$data = '{"PUR_sku":"singleone","PUR_user":"3"}';
$json = json_decode($data,true);
/* Some database stuff ... */
echo "Retour ".print_r($json)." et ".$json['PUR_sku']." et ".$json['PUR_user'];
?>

      

When I launch the application and execute the sendPurchase function, it seems to be ok before the HttpPost is executed. In logcat I get all the logs with the correct parameters, except for the last log "RESULT" which does not appear. This is why I am assuming there is something wrong with the execution of the HttpPost, but in fact I do not know if the problem is from the application side or the PHP script side ... When I execute only the PHP script in the web browser, replacing the first line data on the second, everything is in order. But when it comes to the application, it's not okay ... The Json object sent (hopefully) to the script looks ok too: {"PUR_user": 3, "PUR_sku": "singleone"}

(the sendPurchase function runs in the background).

Any idea on what I am doing wrong? Thank!

/ EDIT /

Here is the logcat for @RyuZz's solution. My code is buying an item, consuming it, and sending the new value to my database on the web server. Buying and consuming is ok, but I am unable to send the values ​​to the web server. Again, when I execute only the PHP script in a web browser, replacing the first line of data with the second, everything is fine. Please note that I have another similar code for registering a user with GCM using HttpClient and this code works fine.

06-25 14:07:12.968: D/IabHelper(21833): Successfully consumed sku: singleconf
06-25 14:07:12.968: D/IabHelper(21833): Ending async operation: consume
06-25 14:07:12.979: D/CONSUME(21833): Consumption finished. Purchase: PurchaseInfo(type:inapp):{"orderId":"12999763169054705758.1353445524837889","packageName":"com.*.*","productId":"singleconf","purchaseTime":1435234296875,"purchaseState":0,"purchaseToken":"bohbcbiigcbidfficbikebnk.AO-J1OzuQ_SsNTG1h9MtUvbaPc3PeN9nBHG-qBOE82ao1rTDFNrgA7tYQcMdECxCVFrrZEn_QifQ28OcIupyesZI-5cjDILFODYpBEaeqMfE0wCAeMFkJLfNUK_TsKPMj7F2sBDdgOYx"}, result: IabResult: Successful consume of sku singleconf (response: 0:OK)
06-25 14:07:12.979: D/CONSUME(21833): You bought & consumed a single conf
06-25 14:07:12.979: D/CONSUME(21833): End consumption flow.
06-25 14:07:12.979: E/Purchase Background(21833): Inside doInBackground
06-25 14:07:12.979: E/sendPurchase(21833): Failed to send HTTP POST request due to: java.lang.NullPointerException

      

+3


source to share


1 answer


You can try the following instead of HttpClient, which is deprecated anyway:

try{
    int pur_user = prefs.getInt("C_user", Integer.MIN_VALUE);

    URL url = new URL("http://www.*.com/includes/purchase.php");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestMethod("POST");

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("PUR_sku", SKU);
    jsonObject.put("PUR_user", pur_user);

    //convert JSONObject to JSON to String
    json = jsonObject.toString();

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(json);
    writer.close();

    responseCode = connection.getResponseCode();

    if(responseCode == 200) {

        InputStream content = connection.getInputStream();
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line).append("\n");
            }
            result = sb.toString();

            //TODO get your stuff from result

            content.close();
        } catch (Exception ex) {
             Log.e(TAG, "Failed to parse JSON due to: " + ex);
        } finally {
             connection.disconnect();
        }
    } else {
        Log.e(TAG, "Server responded with status code: " + responseCode);
    }
} catch(Exception ex) {
    Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}

      

If that doesn't work, please post the logarithm.



Don't forget to fulfill the required permissions in your manifest:

<uses-permission
    android:name="android.permission.INTERNET" />

      

+2


source







All Articles