2013-07-14 98 views
1

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

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

使用logcat的检查你的“错误”相关的Java堆栈跟踪。如果您不了解堆栈跟踪,请编辑您的问题并将其发布到此处。 – CommonsWare

+0

取消注释'e.printStackTrace()'并查看logcat中的异常 – Navid777

+0

请参阅http://stackoverflow.com/questions/22395417/error-strictmodeandroidblockguardpolicy-onnetwork – user4805969

回答

2

似乎是像你正试图使在UI线程http请求。

把你的请求放在另一个线程中。

+0

@ user2068102删除Toast.makeText(getApplicationContext(),“确定“,Toast.LENGTH_LONG).show();从try块和catch块并使用Log.d(“OK”,“Ok”);在try和catch块中,并在logCat中查看结果! –

+0

如果你想使用吐司不是用它为:runOnUiThread(新的Runnable(){ @覆盖 公共无效的run(){ Toast.makeText(.....)显示();} }); –

+0

@ user2068102欢迎:) –

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