Gson解析HTTP請求的響應json數據,Map/Bean

maven依賴:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>

Demo:請求qq,獲取user信息

private static final String QQ_APPID = "XXXXXXX";
private static final String GET_USER_INFO = "https://graph.qq.com/user/get_user_info";
private static final String HEADER = "Content-Type", CONTENNT = "text/xml";


/**
* 利用獲取到的accessToken,openid 去獲取用戶在Qzone的暱稱等信息

* @param request
* @return
*/
public Map<String, Object> getUserInfo(HttpServletRequest request, Map<String, Object> param) {
Map<String, Object> response = new HashMap<String, Object>();
// 發送請求
try {
String token = param.get("accessToken").toString();
String openID = param.get("openID").toString();
String memberKey = param.get("memberKey").toString();
StringBuffer url = new StringBuffer(GET_USER_INFO + "?access_token=" + token + "&oauth_consumer_key=" + QQ_APPID + "&openid=" + openID);
HttpGet httpGet = new HttpGet(url.toString());
httpGet.addHeader(HEADER, CONTENNT);
HttpClient httpClient = HttpClientBuilder.create().build();
// 發送請求,獲取結果
String entSt = EntityUtils.toString(httpClient.execute(httpGet).getEntity());
Gson gson = new Gson();
Map<String,Object> sqlParam = gson.fromJson(entSt,  new TypeToken<HashMap<String,Object>>(){}.getType());//轉Map
if ("0".equals(sqlParam.get("ret").toString())) {
QQUesr qqUesr = new Gson().fromJson(entSt, QQUesr.class);//轉對象
//保存數據
//TODO
response.put("qq_info", qqUesr );
}
}
catch (ClientProtocolException e) {
log.getLogger("qq_s").error("請求https://graph.qq.com/user/get_user_info失敗", param);
e.printStackTrace();
}
catch (Exception e) {
log.getLogger("qq_s").error("QQService.getUserInfo({})", param);
}
return response;
}

PS:demo中的請求是在APP完成QQ登入授權之後哦


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章