package com.example.flightapp;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class APIQuery extends AsyncTask<String,Void,String> {
private static final int TIME_OUT = 5000;
private static final int STREAM_MAX_LENGTH = 10240;
private TextView outputText = null;
public APIQuery(TextView outputText) {
this.outputText = outputText;
}
@Override
protected void onPreExecute() {
super.onPreExecute(); //show location animation
}
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
InputStream inputStream = null;
String result = null;
try {
URl url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(TIME_OUT);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
if (200 == connection.getResponseCode()) {
inputStream = connection.getInputStream();
char[] buffer = new char[STREAM_MAX_LENGTH];
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
reader.read(buffer,0,STREAM_MAX_LENGTH);
result = new String(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try{
inputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
connection.disconnect();
}
return result;
}
@Override
protected void onPostExecute(String result) {
//upgrade UI
outputText.setText(result);
}
}
url资源缺失,需排查
最新推荐文章于 2024-03-28 11:12:41 发布