以下是我使用的代码:
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(500);
urlConnection.setReadTimeout(500);
int statusCode = urlConnection.getResponseCode();
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
}
catch(Exception ex){
Log.d("NetworkUtils", "error in HTTP request");
return null;
}
finally {
Log.d("NetworkUtils", "before disconnect");
if(urlConnection != null) {
urlConnection.disconnect();
}
}
}
发布于 2018-10-10 14:23:24
所以这里有个函数AsyncTask
,它不会抛出NetworkOnMainThreadException
:
public class UrlConnectionTask extends AsyncTask<Bundle, Integer, String> {
private HttpURLConnection urlConnection = null;
private URL url = null;
public UrlConnectionTask(String spec) {
try {
this.url = new URL(spec);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(Bundle... bundles) {
StringBuilder result = new StringBuilder();
if(this.url != null) {
try {
this.urlConnection = (HttpURLConnection) url.openConnection();
this.urlConnection.setConnectTimeout(5000);
this.urlConnection.setReadTimeout(5000);
if(this.urlConnection.getResponseCode() == 200) {
InputStream is = this.urlConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = r.readLine()) != null) {
result.append(inputLine);
}
is.close();
t.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
System.out.println(result);
if (this.urlConnection != null) {
this.urlConnection.disconnect();
}
}
}
https://stackoverflow.com/questions/-100005061
复制相似问题