我到處搜索過,但無法找到答案,如何發出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(本機方法)
您是否在清單中添加了android.permission.INTERNET? –
我添加了該權限,出現以下錯誤:13571-13571/com.example.app E/AndroidRuntime:致命異常:主要 java.lang.IllegalStateException:無法執行活動的方法 –
請包括* complete *錯誤信息(理想情況下整個堆棧跟蹤 - 您應該記錄,而不僅僅是消息)在您的問題中,而不是在評論中。此外,請在您的問題中對代碼進行格式化,以使其更具可讀性。 –