Android HttpClient response

345 views Asked by At

I'm trying to send json data to a php script from my Android application with HttpClient, and get the 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 the 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 app and execute sendPurchase function, it seems to be ok until the execution of the HttpPost. In the logcat i get all the logs with correct params, except the last log "RESULT" that does not appear. That's why i guess something is going wrong with the HttpPost execution, but actually i don't know if the problem comes from the application side or the php script side... When i execute the php script alone in a web browser, replacing first $data line by the second one, everything is ok. But when it comes from the application it's not ok... The Json Object sent (i hope) to the script seems ok too : {"PUR_user":3,"PUR_sku":"singleone"}

(the sendPurchase function is executed in Background).

Any idea about what i'm doing wrong ? Thanks !

/EDIT/

Here is the logcat for @RyuZz solution. My code is about purchasing an item, consume it and send new value to my database on a web server. The purchase & consume are ok, but i can't send the values to the web server. And again, when i execute the php script alone in a web browser, replacing first $data line by the second one, everything is ok. Note that i have another similar code to register user to GCM, using HttpClient, and that 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
1

There are 1 answers

3
RyuZz On

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

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 this isn't working, please post the logcat.

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

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