通常情况下都应该将这些通用的网络操作提取到一个公共的类里,并提供一个静态的方法,当想要发起网络请求的时候只需要简单的调用一下这个方法即可。
在utils包下新建一个网络请求的工具类HttpUtil:
package com.dy.ustc.weatherpro.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
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);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if (listener != null) {
// 回调onFinish()方法
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
// 回调onError()方法
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
使用的是HttpURLConnection.在获取到服务器的数据后,我们就可以对他进行解析和处理,但是需要注意,网络操作通常都属于耗时的操作。这里使用了Java的回调机制。首先定义了一个接口:
package com.dy.ustc.weatherpro.utils;
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
onFinish代表服务器成功响应我们的请求调用。
onError表示进行网络操作的时候出现错误进行调用。
如果直接在sendHttpRequest方法中开启一个子线程,那么服务器响应的数据是无法进行返回的,所有的耗时的逻辑都是在子线程中进行,sendHttpRequest方法会在服务器还未来得及响应就执行结束了,当然也就无法返回响应的数据了。
调用他的时候:
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
Log.i(TAG, response.toString());
}
@Override
public void onError(Exception e) {
System.out.println(e.getMessage() + "哈哈,解析错误");
Log.i(TAG, e.getMessage() + "哈哈,解析错误");
}
});
再在utils包中新建Utility类,用来返回省市县的数据:
数据:“代号|城市,代号|城市”,所以得使用正则表达式匹配:
/**
* 解析和处理服务器返回的省级数据
*/
public synchronized static boolean handleProvincesResponse(
CoolWeatherDB coolWeatherDB, String response) {
if (!TextUtils.isEmpty(response)) {
String[] allProvinces = response.split(",");
if (allProvinces != null && allProvinces.length > 0) {
for (String p : allProvinces) {
String[] array = p.split("\\|");
Province province = new Province();
province.setProvinceCode(array[0]);
province.setProvinceName(array[1]);
// 将解析出来的数据存储到Province表
coolWeatherDB.saveProvince(province);
}
return true;
}
}
return false;
}
/**
* 解析和处理服务器返回的市级数据
*/
public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB,
String response, int provinceId) {
if (!TextUtils.isEmpty(response)) {
String[] allCities = response.split(",");
if (allCities != null && allCities.length > 0) {
for (String c : allCities) {
String[] array = c.split("\\|");
City city = new City();
city.setCityCode(array[0]);
city.setCityName(array[1]);
city.setProvinceId(provinceId);
// 将解析出来的数据存储到City表
coolWeatherDB.saveCity(city);
}
return true;
}
}
return false;
}
/**
* 解析和处理服务器返回的县级数据
*/
public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB,
String response, int cityId) {
if (!TextUtils.isEmpty(response)) {
String[] allCounties = response.split(",");
if (allCounties != null && allCounties.length > 0) {
for (String c : allCounties) {
String[] array = c.split("\\|");
County county = new County();
county.setCountyCode(array[0]);
county.setCountyName(array[1]);
county.setCityId(cityId);
// 将解析出来的数据存储到County表
coolWeatherDB.saveCounty(county);
}
return true;
}
}
return false;
}