从android调用外部URL并获得响应

时间:2011-02-03 17:43:36

标签: android url call

我正在尝试使用

在Android中调用URL
HttpClient mClient= new DefaultHttpClient()

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

mClient.execute(get);

HttpResponse res = mClient.execute(get);

但是,我没有得到任何回应。如何在Android中调用URL?

4 个答案:

答案 0 :(得分:7)

这是一个完整的例子:

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

使用协议“http://

的网址
"http://www.stackoverflow.com" instead of just "www.stackoverflow.com"

请务必将此权限包含在androidmanifest.xml

<uses-permission
    android:name="android.permission.INTERNET" />

答案 1 :(得分:3)

您必须在AndroidManifest.xml文件中添加<uses-permission android:name="android.permission.INTERNET"/>。在<manifest>元素下。

答案 2 :(得分:0)

您正在拨打mClient.execute(get)两次。

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

答案 3 :(得分:0)

改用排球。

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