1

I'm trying to set up a PHP API for my Android application to interact with, my problem is that the post data never seems to get posted and I can never retrieve the response body (HTML/TXT) from the URL given.

My code

Thread thread = new Thread(new Runnable(){
        @Override
        public void run() {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost clientpost = new HttpPost("http://192.168.1.129/updateMain.php");

                try {
                    List<NameValuePair> params = new ArrayList<NameValuePair>(2);

                    params.add(new BasicNameValuePair("_id", "1"));
                    params.add(new BasicNameValuePair("job_name", "Test"));

                    clientpost.setEntity(new UrlEncodedFormEntity(params));

                    HttpResponse response = client.execute(clientpost);

                    String responseBody = EntityUtils.toString(response.getEntity());

                } catch(Exception e)
                {
                    Log.e("Error", e.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

If I can post data then I will be able to post JSON to the server and retrieve JSON from the server, thus overcoming the biggest hurdle I have at the moment.

Any help greatly appreciated.

2
  • 2
    Consider using Volley library, it is faster and easier. Commented Aug 26, 2015 at 12:35
  • I checked volley out, again the response never gets printed... that would be a different question on its own though. Thanks for the advice. Commented Aug 26, 2015 at 13:28

2 Answers 2

1
public String getResponse(String url, List<NameValuePair> nameValuePairs) {

    url = url.replaceAll(" ", "%20");
    String result = "ERROR";
    Log.d("Pair", nameValuePairs.toString());
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams http_params = httpclient.getParams();
    http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
            HttpVersion.HTTP_1_1);
    HttpConnectionParams.setConnectionTimeout(http_params, TIMEOUT);
    HttpConnectionParams.setSoTimeout(http_params, TIMEOUT);
    HttpResponse response = null;

    try {
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        result = "ERROR";
    } catch (IOException e) {
        e.printStackTrace();
        result = "ERROR";
    }

    try {
        // Get hold of the response entity
        HttpEntity entity = null;
        if (response != null) {
            entity = response.getEntity();
        }
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            result = convertStreamToString(inputStream);
        }

    } catch (IOException e) {
        result = "ERROR";
    }

    httpclient.getConnectionManager().shutdown();
    return result;
}

Use this Method with AsyncTask or background thread

Sign up to request clarification or add additional context in comments.

1 Comment

Just prints error, never prints the stack trace. This method all seems very complicated for such a simple task? I'm probably wrong, but it's a lot to take in.
1

This one is working for me. Please do take care of exceptions ans error handling. Key121 variable is your php file url.

  class callServiceTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params) {
    loginCheck();
    return null;
    }
} 
public void loginCheck()
{
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("aa","11"));   
nameValuePairs.add(new BasicNameValuePair("bb","22"));

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(KEY_121);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e)
    {
        Log.e("log_tag", "Error:"+e.toString());
    }
//convert response to string
    try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
    is.close();
    result=sb.toString();
    Log.e("log_tag", "----------------"+result);
    }catch(Exception e){
    Log.e("log_tag", "Error converting result "+e.toString());
    }
}

You need to use stream and buffered reader for analysing response. Do check and let us know.

3 Comments

Unfortunately doesn't work for me, the response never gets logged Log.d("Response", result) never prints anything. Also I did add the catch and am running this in a different thread.
@JamesParker : Complete class code is updated in answer. Check and let me know your output/error.
Here I will require your php file too as you say even other methods don't give output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.