我想从url收到404错误,但我使用的代码总是会产生错误:
public String getRespond(String request) {
try{
URL url=new URL (request);
URLConnection connection=url.openConnection();
InputStream in=new BufferedInputStream(connection.getInputStream());
Scanner scanner =new Scanner(in);
String response=scanner.nextLine();
scanner.close();
return response;
}
catch (Exception e){
return null;
}
}
错误出现在“in = new ...”中,如果出现404错误,我无法知道。 这是错误:
02-23 11:42:42.869 20413-20413/com.mappleapps.tm2ibz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mappleapps.tm2ibz, PID: 20413
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
感谢!!!
答案 0 :(得分:1)
在应用程序的主线程上不再允许HTTP请求。
因此,您应该使用并行Thread
,或者更简单地使用AsyncTask
class ResponseTask extends AsyncTask<String, Void, String> {
public static interface ResponseTaskListener {
void onResponse(String response);
void onException(Exception e);
}
private ResponseTaskListener listener;
private Exception e;
public ResponseTask(ResponseTaskListener listener) {
this.listener = listener;
}
protected String doInBackground(String... urls) {
try {
String request = urls[0];
URL url=new URL (request);
URLConnection connection=url.openConnection();
InputStream in=new BufferedInputStream(connection.getInputStream());
Scanner scanner =new Scanner(in);
String response=scanner.nextLine();
scanner.close();
return response;
} catch (Exception e){
this.e = e;
return null;
}
}
// String response = what is returned by doInBackground
protected void onPostExecute(String response) {
if (this.listener != null) {
if (this.e != null) {
this.listener.onException(this.e);
} else {
this.listener.onResponse(response);
}
}
}
}
然后执行此请求,您可以:
new ResponseTask(new ResponseTaskListener() {
public void onResponse(String response) {
// Play with the response
}
public void onException(Exception e) {
// Play with the exception
}
}).execute(urlToRssFeed);