文章目录
- 一、Http
- 1、HttpURLConnection
- 2、OKHttp
- 二、解析JSON格式数据
- 1、使用JSONObject
- 2、使用GSON解析JSON数据
一、Http
1、HttpURLConnection
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 下面对获取到的输入流进行处理
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
response.append(line);
}
showRespnse(response.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if (reader != null){
try {
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (connection != null){
connection.disconnect();
}
}
}
}).start();
}
2、OKHttp
导入依赖:implementation 'com.squareup.okhttp3:okhttp:3.10.0'
private void sendRequestWithOkHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showRespnse(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
二、解析JSON格式数据
1、使用JSONObject
private void parseJSONWithJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
Log.d(TAG,"id is " + id);
Log.d(TAG,"name is " + name);
Log.d(TAG,"version is " + version);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
2、使用GSON解析JSON数据
导入依赖:implementation 'com.google.code.gson.2.10.1'
主要是将一个JSON格式的字符串自动映射成一个对象,无需手动解析。
假如有个Person类,包含name和age字段,调用如下代码就可以将JSON数据解析成一个Person对象了。
Gson gson = new Gson();
Person person = gson.fromJson(jsonData,Person.class);
如果是JSON数组,需要借助TypeToken将期望的数据类型传入到fromJson方法中,如下所示:
List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());
private void parseJSONWithGSON(String jsonData){
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
for (App app : appList){
Log.d(TAG,"id is " + app.getId());
Log.d(TAG,"name is " + app.getName());
Log.d(TAG,"version is " + app.getVersion());
}
}