2014-02-27 127 views
0

我到處搜索過,但無法找到答案,如何發出HTTP請求?我嘗試了幾種可能性,但都沒有成功。我不斷收到錯誤。在Android上的HTTP請求無法正常工作

InputStream is = null; 
// Only display the first 500 characters of the retrieved 
// web page content. 
int len = 500; 

try { 
URL url = new URL(myurl); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setReadTimeout(10000 /* milliseconds */); 
conn.setConnectTimeout(15000 /* milliseconds */); 
conn.setRequestMethod("GET"); 
conn.setDoInput(true); 
// Starts the query 
conn.connect(); 
int response = conn.getResponseCode(); 
Log.d("Debug:", "The response is: " + response); 
is = conn.getInputStream(); 

// Convert the InputStream into a string 
String contentAsString = readIt(is, len); 
return contentAsString; 

// Makes sure that the InputStream is closed after the app is 
// finished using it. 
} 
catch(Exception ex) 
{ 
    Log.v("Message: ", ex.getMessage()); 
    return "Helemaal niks!"; 
} 
finally { 
    if (is != null) { 
     is.close(); 
    } 
} 

02-27 17:52:58.611 13571-13571/com.example.app E/AndroidRuntime:致命異常:主 java.lang.IllegalStateException:無法在機器人執行活動 的方法。 view.View $ 1.onClick(View.java:3838) at android.view.View.performClick(View.java:4475) at android.view.View $ PerformClick.run(View.java:18786) at android .os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app .ActivityThread.main(ACTI vityThread.java:5419) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1187) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 在dalvik.system.NativeStart.main(本機方法)

+0

您是否在清單中添加了android.permission.INTERNET? –

+0

我添加了該權限,出現以下錯誤:13571-13571/com.example.app E/AndroidRuntime:致命異常:主要 java.lang.IllegalStateException:無法執行活動的方法 –

+0

請包括* complete *錯誤信息(理想情況下整個堆棧跟蹤 - 您應該記錄,而不僅僅是消息)在您的問題中,而不是在評論中。此外,請在您的問題中對代碼進行格式化,以使其更具可讀性。 –

回答

0

所有的Web服務調用和等應該總是的AsyncTask內進行。

這有助於它在執行時不會讓應用程序等待。

下面是一個示例代碼,可以幫助您瞭解如何進行網絡調用。

try { 


     HttpClient httpclient = new DefaultHttpClient(); 

     HttpParams httpParameters = new BasicHttpParams(); 
     HttpConnectionParams.setConnectionTimeout(httpParameters, 2000); 
     HttpConnectionParams.setSoTimeout(httpParameters, 2000); 
     httpclient = new DefaultHttpClient(httpParameters); 

     HttpGet request = new HttpGet(Constants.CHECK_UPDATE_URL); 

     String responseString = null; 

     HttpResponse response = httpclient.execute(request); 
     StatusLine statusLine = response.getStatusLine(); 

     if (statusLine.getStatusCode() == HttpStatus.SC_OK) { 

      // Logging Server Responded 

      LogActions.systemActions("Server Responded"); 

      ByteArrayOutputStream out = new ByteArrayOutputStream(); 
      response.getEntity().writeTo(out); 
      out.close(); 


          //do your tasks here 

     } 

    } catch (Exception e) { 

     Log.e("Exception", "An impossible exception", e); 
    } 
0

如果您只想做一個HTTP請求,你可以使用這個代碼而不是你的代碼。

try{ 
    String result = null; 
    HttpClient httpClient = new DefaultHttpClient(); 
    String myUrl = "your url"; 
    HttpContext localContext = new BasicHttpContext(); 
    HttpGet httpGet = new HttpGet(myUrl); 
    HttpResponse response = httpClient.execute(httpGet, localContext); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(
      response.getEntity().getContent())); 

    String line = null; 
    while ((line = reader.readLine()) != null) { 
     result += line + "\n"; 
    } 
    return result; 
}catch(Exception ex) 
{ 
    Log.v("Message: ", ex.getMessage()); 
    return "Helemaal niks!"; 
} 
相關問題