1

I am trying to call a URL in android using

HttpClient mClient= new DefaultHttpClient()

HttpGet get = new HttpGet("www.google.com ");

mClient.execute(get);

HttpResponse res = mClient.execute(get);

But, I did not get any response. How can I call URL in Android?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Lalit Chattar
  • 704
  • 4
  • 10
  • 24

4 Answers4

7

This is a complete example:

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(yourURL);
        HttpResponse response = httpclient.execute(httpget);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {                    
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        Log.v("My Response :: ", result);

use the url with the protocol "https://"

"https://www.stackoverflow.com" instead of just "www.stackoverflow.com"

be sure to have this permission into your androidmanifest.xml

<uses-permission
    android:name="android.permission.INTERNET" />
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • Post a copy of your log output if you can. Also ensure your app has the uses_internet permission set in the manifest. – FoamyGuy Feb 03 '11 at 20:19
  • For newer Android versions, you need to use https or make exceptions as described here: https://stackoverflow.com/a/50834600/2738240 Otherwise you will get errors (see Run/Debug log in Android Studio). – Matthias Luh May 10 '20 at 19:49
3

You must add <uses-permission android:name="android.permission.INTERNET"/> in the AndroidManifest.xml file. Under <manifest> element.

0

You are calling mClient.execute(get) twice.

mClient.execute(get);
HttpResponse res = mClient.execute(get); 
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
Magno C
  • 1,922
  • 4
  • 28
  • 53
0

Use volley instead.

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String getUrl = "http://www.google.com";
    StringRequest getRequest = new StringRequest(Request.Method.GET, getUrl, new Response.Listener<String>() {
        @Override
        public void onResponse (String response) {
            Log.v(TAG, "GET response: " + response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse (VolleyError error) {
            Log.v(TAG, "Volley GET error: " + error.getMessage());
        }
    });
    requestQueue.add(getRequest);
kjdion84
  • 9,552
  • 8
  • 60
  • 87