Call external URL from android and get response

半世苍凉 提交于 2019-12-21 23:07:32

问题


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

"http://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);


来源:https://stackoverflow.com/questions/4889618/call-external-url-from-android-and-get-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!