简体   繁体   中英

How to make Apache HTTP request from AsyncTask

I am trying to get json values using HTTP POST method. So far I am able to receive values with GET method. And here is the code so far:

 private class SimpleTask extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        // Create Show ProgressBar
    }

    protected String doInBackground(String... urls)   {
        String result = "";
        try {

            HttpGet httpGet = new HttpGet(urls[0]);
            HttpClient client = new DefaultHttpClient();

            HttpResponse response = client.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                InputStream inputStream = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader
                        (new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
            }

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }
        //Log.w("PREMIERE::::",result);
        return result;
    }

    protected void onPostExecute(String jsonString)  {
        // Dismiss ProgressBar
        showData(jsonString);
    }
}

Now assume if I have a field number with value= +919061037828 , how do I adapt my code to get result in POST method?

This is how I call my AsyncTask :

public static final String URL = "https://api.eduknow.info/mobile/get_details";
new SimpleTask().execute(URL);

I guess your problem is with parameters.

Try sth like this:

 HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("your url");
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

        nameValuePair.add(new BasicNameValuePair("username",    "username"));
        nameValuePair.add(new BasicNameValuePair("lang", "en"));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePair);
        HttpResponse response = httpClient.execute(httpPost);

Hope it will help.

EDIT And I just found another possible solution for your problem: Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM