Call external URL from android and get response

2020-08-01 05:26发布

问题:

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?

回答1:

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" />


回答2:

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



回答3:

You are calling mClient.execute(get) twice.

mClient.execute(get);
HttpResponse res = mClient.execute(get); 


回答4:

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);


标签: android url call