1

对不起,我是世界 java 和 android 的新手。我想了解为什么它总是响应错误。谢谢!

try {
            HttpClient client = new DefaultHttpClient();  
            String getURL = "http://www.google.com";
            HttpGet get = new HttpGet(getURL);
            HttpResponse responseGet = client.execute(get);  
            HttpEntity resEntityGet = responseGet.getEntity();  
            if (resEntityGet != null) {  
            Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
             }
    } catch (Exception e) {
        //e.printStackTrace();
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
    }

进口

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

是的,我进入了互联网许可

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testhttp"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
4

2 回答 2

2

似乎您正试图在UI 线程http中发出请求。

将您的请求放在另一个线程中。

于 2013-07-14T17:03:07.917 回答
0

您还可以使用此代码发出 HTTP 请求:

public class RequestClient extends AsyncTask<String, Void, String>{
        Context context;

        public RequestClient(Context c) {
            context = c;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... aurl){
        String responseString="";
        HttpClient client = null;
        try {
             client = new DefaultHttpClient();  
             HttpGet get = new HttpGet(LoginActivity.url);
             HttpResponse responseGet = client.execute(get);  
             HttpEntity resEntityGet = responseGet.getEntity();  
             if (resEntityGet != null) {  
                 responseString = EntityUtils.toString(resEntityGet);
                 Log.i("GET RESPONSE", responseString.trim());
             }
        } catch (Exception e) {
            Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
        }
            Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
            client.getConnectionManager().shutdown();
         return responseString.trim();

        }


        @Override
        protected void onPostExecute(String response) {
             super.onPostExecute(response); 
            }
    }
于 2013-07-17T12:37:10.787 回答