11

I need Sync or Async HTTP Post/Get to get HTML data from Web-Service. I search this whole internet but I can't give good result.

I tried to use this examples:

but nothing of them working for me.

HttpClient and HttpGet is cross out, error is :

"org.apache.http.client.HttpClient is deprecated "

Code:

try
{
    HttpClient client = new DefaultHttpClient();
    String getURL = "google.com";
    HttpGet get = new HttpGet(getURL);
    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();
    if (resEntityGet != null)
    {
        //do something with the response 
    }
}
catch (Exception e)
{
    e.printStackTrace();
}
9
  • may be if you post what is the error in your try may lead to result.
    – Sree
    Commented Jun 19, 2015 at 11:22
  • I can't run app because HttpClient and HttpGet is cross out, error is : "org.apache.http.client.HttpClient is deprecated " CODE: try { HttpClient client = new DefaultHttpClient(); String getURL = "google.com"; HttpGet get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response } } catch (Exception e) { e.printStackTrace(); } Commented Jun 19, 2015 at 11:25
  • you need to find why you cant run
    – Sree
    Commented Jun 19, 2015 at 11:26
  • compilator get me this error: "org.apache.http.client.HttpClient is deprecated " Commented Jun 19, 2015 at 11:30
  • mkyong.com/java/the-type-defaulthttpclient-is-deprecated
    – Sree
    Commented Jun 19, 2015 at 11:34

3 Answers 3

10

The example I have posted below is based on an example that I found on the Android Developer Docs. You can find that example HERE, look at that for a more comprehensive example.

You will be able to make any http requests with the following

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new DownloadTask().execute("http://www.google.com/");
    }

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

        @Override
        protected String doInBackground(String... params) {
            //do your request in here so that you don't interrupt the UI thread
            try {
                return downloadContent(params[0]);
            } catch (IOException e) {
                return "Unable to retrieve data. URL may be invalid.";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            //Here you are done with the task
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
        }
    }

    private String downloadContent(String myurl) throws IOException {
        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);
            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);
        return new String(buffer);
    }
}

You can play around with the code to suit your needs

6
  • Compilator do not recognize: HttpURLConnection, URL, openConnection() and etc. see image: postimg.org/image/sjaav97yx Commented Jun 19, 2015 at 12:09
  • I added library but still is some errors, see screen: postimg.org/image/re791wksx Commented Jun 19, 2015 at 12:19
  • I'm missing this: private String downloadContent(String myurl) throws IOException and at this moment errors disrepair :):) thank you for grate help, I'm testing my code and give you feedback. Commented Jun 19, 2015 at 12:25
  • Pleasure, remember to mark as the answer if it helped. Commented Jun 19, 2015 at 12:31
  • I have already mark your answer. Thank you A lot Neil :) you save my 3 days work Commented Jun 19, 2015 at 12:44
4

You can use Volley which gives you everything you need. If you decide to use AsyncTask and program it yourself, I'd recommend to not have AsyncTask inside your Activity, but rather put it in a wrapper class and use a callback to that. This keeps your Activity clean and makes the network code reusable. Which is more or less what they did in Volley.

1
  • 1
    Volley is a great alternative, and actually a better option! Commented Jun 19, 2015 at 12:32
0
**Async POST & GET request**

public class FetchFromServerTask extends AsyncTask<String, Void, String> {
    private FetchFromServerUser user;
    private int id;

    public FetchFromServerTask(FetchFromServerUser user, int id) {
        this.user = user;
        this.id = id;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        user.onPreFetch();
    }

    @Override
    protected String doInBackground(String... params) {

        URL urlCould;
        HttpURLConnection connection;
        InputStream inputStream = null;
        try {
            String url = params[0];
            urlCould = new URL(url);
            connection = (HttpURLConnection) urlCould.openConnection();
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setRequestMethod("GET");
            connection.connect();

            inputStream = connection.getInputStream();

        } catch (MalformedURLException MEx){

        } catch (IOException IOEx){
            Log.e("Utils", "HTTP failed to fetch data");
            return null;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    protected void onPostExecute(String string) {

        //Do your own implementation
    }
}


****---------------------------------------------------------------***


You can use GET request inn any class like this:
new FetchFromServerTask(this, 0).execute(/*Your url*/);

****---------------------------------------------------------------***

For Post request just change the : connection.setRequestMethod("GET"); to

connection.setRequestMethod("POST");

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.