OKHTTP解析json資料
先上代碼例子:
public class OKHTTPdemo {
public static void main(String[] args) throws IOException {
//聯網擷取資料,傳回值為String型的
OKHTTPdemo example = new OKHTTPdemo();
ObjectMapper mapper = new ObjectMapper();
String response = example.run("https://api.douban.com/v2/movie/subject/1764796");
//json資料的解析
JsonNode jsonNode = mapper.readTree(response);
String max = jsonNode.path("rating").path("average").asText();
System.out.println(max);
}
private String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
注意的是:需要build path添加開源架構OKHTTP.jar和okio.jar