1.HttpURLConnecttion
通过HttpURLConnection可以进行Http请求
HttpURLConnection的用法:
- 调用URL.openConnection得到URLConnection并转型为HttpURLConection
- 设置请求内容,比如请求方法为“GET”
- 使用connect()发送请求
- getResponseCode(),getInputStream()分别得到状态码和输入流
- 最后记得调用disconection()关闭连接
以下是代码实列:
public String httpRequest() throws IOException {
StringBuilder result=new StringBuilder();
URL url=new URL("http://apis.baidu.com/apistore/weatherservice/weather?citypinyin=shanghai");
//发送网络请求
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("apikey",APIKEY);
urlConnection.connect();
int response=urlConnection.getResponseCode();
//获取输入流
InputStream in=urlConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
//关闭连接
urlConnection.disconnect();
String data;
//从输入流中读取出字符串
while((data=reader.readLine())!=null){
result.append(data);
result.append("\r\n");
}
//关闭输入流
reader.close();
return result.toString();
}
2.Json数据解析
使用JSONObject和JSONArray解析
API:
JSONObject(String),从string构造一个JSONObject,解析失败时抛出JSONException
JSONObject js=new JSONObject(jsonString);
JSONObject.get(String):Object 返回名字所映射的对象,如果没有则抛出JSONException
JSONObject.getJSONObject(String):JSONObject 返回名字所映射的JSONObject对象,如果没有则抛出JSONException
JSONObject.getJSONArray(String):JSONArray 返回名字所映射的JSONArray对象,如果没有则抛出JSONException
JSONObject.getXXX(String):XXX 返回名字所映射的基本数据类型,如果没有则抛出JSONException
代码:
public static CityList[] getCityList(String jsString) throws JSONException {
ArrayList<CityList> list=new ArrayList<>();
//通过Json String创建JSONObject
JSONObject jsObj=new JSONObject(jsString);
if(jsObj.getInt("errNum")!=-1){
//如果请求数据正确,则继续解析数据
JSONArray js=jsObj.getJSONArray("retData");
if (js!=null){
JSONObject jsonObject;
for(int i=0;i<js.length();i++){
try {
CityList city=new CityList();
jsonObject=js.getJSONObject(i);
city.setProvince_cn(jsonObject.getString("province_cn"));
city.setName_cn(jsonObject.getString("name_cn"));
city.setDistrict_cn(jsonObject.getString("district_cn"));
city.setName_en(jsonObject.getString("name_en"));
city.setArea_id(jsonObject.getString("area_id"));
list.add(city);
} catch (JSONException e) {
e.printStackTrace();
}
}
return list.toArray(new CityList[list.size()]);
}else return null;
}else return null;
}
Json数据:
{
"errNum": 0,
"errMsg": "success",
"retData": [
{
"province_cn": "上海",
"district_cn": "上海",
"name_cn": "上海",
"name_en": "shanghai",
"area_id": "101020100"
},
{
"province_cn": "上海",
"district_cn": "上海",
"name_cn": "闵行",
"name_en": "minhang",
"area_id": "101020200"
},
{
"province_cn": "上海",
"district_cn": "上海",
"name_cn": "宝山",
"name_en": "baoshan",
"area_id": "101020300"
},.....
总的来说这种方式需要手动的一层层解析,而通过一些工具比如:Gson,fastjson等可以使解析过程变得更简单
使用GSON解析
API:
Gson.fromJson(String json, Class<T> class):T 提供json数据和指定的类,将json解析为指定类的java对象
Gson.toJson(Object obj):String 将java对象解析为json
代码:
Gson gson=new Gson();
RequestData data=gson.fromJson(jsString,RequestData.class);
public class RequestData {
private String errNum;
private String errMsg;
private WeatherData retData;
@Override
public String toString() {
return "WeatherInfo{" +
"errNum='" + errNum + '\'' +
", errMsg='" + errMsg + '\'' +
", retData=" + retData +
'}';
}...
public class WeatherData {
//如果域名与json数据不同时可以使用注解
@SerializedName("city")
private String cityName;
private String pinyin;
@SerializedName("citycode")
private String cityCode;
private String weather;
private String date;
private String time;
@SerializedName("temp")
private String tmp;
private String l_tmp;
private String h_tmp;
@Override
public String toString() {
return "WeatherData{" +
"cityName='" + cityName + '\'' +
", pinyin='" + pinyin + '\'' +
", cityCode='" + cityCode + '\'' +
", weather='" + weather + '\'' +
", date='" + date + '\'' +
", time='" + time + '\'' +
", tmp='" + tmp + '\'' +
", l_tmp='" + l_tmp + '\'' +
", h_tmp='" + h_tmp + '\'' +
'}';
}.....
json数据
{
"errNum": 0,
"errMsg": "success",
"retData": {
"city": "上海",
"pinyin": "shanghai",
"citycode": "101020100",
"date": "16-08-28",
"time": "18:00",
"postCode": "200000",
"longitude": 121.445,
"latitude": 31.213,
"altitude": "19",
"weather": "多云",
"temp": "22",
"l_tmp": "22",
"h_tmp": "30",
"WD": "西北风",
"WS": "3-4级(10~17km/h)",
"sunrise": "05:28",
"sunset": "18:22"
}
}
Gson还支持更复杂json解析,官方使用说明Gson User Guide