因为我们在一个程序中要多次使用网络请求,所以需要封装一个工具类方便使用
public class HttpUtil {
public static void sendHttpRequest(final String address, final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if (listener != null) {
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
感觉这个图不错,很帮助理解,就拿过来用一下
然后新建一个接口(为什么要用接口,是因为我们调用sendHttpRequest无法返回响应的数据,所以需要回调机制)
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
使用实例:和json解析联系起来
首先这是我在本地服务器下的json文件(用的免费的tomcat服务器)
这是解析函数
private void parseJsonObject(String jsondata) throws JSONException {
JSONArray jsonArray = new JSONArray(jsondata);
for (int i=0;i
这是在主函数中直接调用我们刚才封装好的工具类
HttpUtil.sendHttpRequest("http://10.0.2.2:8080/test/get_data.json", new HttpCallbackListener() {
@Override
public void onFinish(String response) {
//在这里根据返回内容进行具体的逻辑
Log.e("TAG","---------"+response);
String responseData = null;
responseData = response;
try {
parseJsonObject(responseData);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(Exception e) {
//在这里对异常情况进行处理
}
});
可以看到运行结果了(这里用log.e打印出了解析结果)