HttpClient相比傳統JDK自帶的URLConnection,增長了易用性和靈活性(具體區別,往後咱們再討論),它不只是客戶端發送Http請求變得容易,並且也方便了開發人員測試接口(基於Http協議的),即提升了開發的效率,也方便提升代碼的健壯性。所以熟練掌握HttpClient是很重要的必修內容,掌握HttpClient後,相信對於Http協議的瞭解會更加深刻。java
工具類:git
httpPost:github
package com.example.demo.util; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLDecoder; /** * Created by ningcs on 2017/7/4. */ public class HttpRequestUtils { private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); //日誌記錄 /** * httpPost * * @param url 路徑 * @param jsonParam 參數 * @return */ public static JSONObject httpPost(String url, JSONObject jsonParam) { return httpPostJSONObject(url, jsonParam, false); } /** * post請求 * * @param url url地址 * @param jsonParam 參數 * @param noNeedResponse 不須要返回結果 * @return */ public static JSONObject httpPostJSONObject(String url, JSONObject jsonParam, boolean noNeedResponse) { //post請求返回結果 DefaultHttpClient httpClient = new DefaultHttpClient(); JSONObject jsonResult = null; HttpPost method = new HttpPost(url); try { if (null != jsonParam) { //解決中文亂碼問題 StringEntity entity = new StringEntity(jsonParam.toString()); System.out.println("entity" + jsonParam.toString()); System.out.println("entity" + entity.toString()); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } HttpResponse result = httpClient.execute(method); url = URLDecoder.decode(url, "UTF-8"); /**請求發送成功,並獲得響應**/ if (result.getStatusLine().getStatusCode() == 200) { String str = ""; try { /**讀取服務器返回過來的json字符串數據**/ str = EntityUtils.toString(result.getEntity()); if (noNeedResponse) { return null; } /**把json字符串轉換成json對象**/ jsonResult = JSONObject.fromObject(str); } catch (Exception e) { logger.error("post請求提交失敗:" + url, e); } } } catch (IOException e) { logger.error("post請求提交失敗:" + url, e); } return jsonResult; } /** * 發送get請求 * * @param url 路徑 * @return */ public static JSONObject httpGetJsonObject(String url) { //get請求返回結果 JSONObject jsonResult = null; String strResult = ""; try { DefaultHttpClient client = new DefaultHttpClient(); //發送get請求 HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); /**請求發送成功,並獲得響應**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**讀取服務器返回過來的json字符串數據**/ strResult = EntityUtils.toString(response.getEntity()); /**把json字符串轉換成json對象**/ jsonResult = JSONObject.fromObject(strResult); url = URLDecoder.decode(url, "UTF-8"); } else { logger.error("get請求提交失敗:" + url); } } catch (IOException e) { logger.error("get請求提交失敗:" + url, e); } return jsonResult; } /** * 發送get請求 * * @param url 路徑 * @return */ public static String httpGet(String url) { //get請求返回結果 JSONObject jsonResult = null; String strResult = ""; try { DefaultHttpClient client = new DefaultHttpClient(); //發送get請求 HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); /**請求發送成功,並獲得響應**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**讀取服務器返回過來的json字符串數據**/ strResult = EntityUtils.toString(response.getEntity()); /**把json字符串轉換成json對象**/ // jsonResult = JSONObject.fromObject(strResult); url = URLDecoder.decode(url, "UTF-8"); } else { logger.error("get請求提交失敗:" + url); } } catch (IOException e) { logger.error("get請求提交失敗:" + url, e); } return strResult; } /** * 發送get請求 * * @param url 路徑 * @return */ public static String httpGetArray(String url) { //get請求返回結果 JSONArray jsonResult = null; String strResult = ""; try { DefaultHttpClient client = new DefaultHttpClient(); //發送get請求 HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); /**請求發送成功,並獲得響應**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**讀取服務器返回過來的json字符串數據**/ strResult = EntityUtils.toString(response.getEntity()); /**把json字符串轉換成json對象**/ // jsonResult = JSONObject.fromObject(strResult); url = URLDecoder.decode(url, "UTF-8"); } else { logger.error("get請求提交失敗:" + url); } } catch (IOException e) { logger.error("get請求提交失敗:" + url, e); } return strResult; } }
gson:web
package com.example.demo.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.List; /** * Created by ningcs on 2017/7/26. */ public class GsonUtils { // 將Json數據解析成相應的映射對象 public static <T> T parseJsonWithGson(String jsonData, Class<T> type) { Gson gson = new Gson(); T result = gson.fromJson(jsonData, type); return result; } /** * Exception:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT * 錯誤緣由: * 應該以JsonArray的形式接收。 * JsonArray json =new JsonArray(); */ // 將Json數組解析成相應的映射對象列表 public static <T> List<T> parseJsonArrayWithGson(String jsonData, Class<T> type) { Gson gson = new Gson(); List<T> result = gson.fromJson(jsonData, new TypeToken<List<T>>(){ }.getType()); return result; } }
實現類 service:spring
package com.example.demo.service.impl; import com.example.demo.entity.MatchDay; import com.example.demo.entity.User; import com.example.demo.model.MatchDayModel; import com.example.demo.service.UserService; import com.example.demo.util.GsonUtils; import com.example.demo.util.HttpRequestUtils; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; /** * Created by ningcs on 2017/7/26. */ @Service public class UserServiceImpl implements UserService { @Value("${get_user_ip}") private String url; //返回json格式 @Override public JSONObject getUserInfo(String idNumber) { String params = "?" + "player_id_number=" + idNumber; JSONObject result = HttpRequestUtils.httpGetJsonObject(url + "/user/getUser.do" + params); return result; } //json格式轉對象 @Override public User getUser(String idNumber) { String params = "?" + "player_id_number=" + idNumber; String str = HttpRequestUtils.httpGet(url + "/apply/getMatchApplyDayList.do" + params); User user = GsonUtils.parseJsonWithGson(str, User.class); return user; } //json格式數組 @Override public List<User> getUserList(String idNumber) { String params = "?" + "player_id_number=" + idNumber; String str = HttpRequestUtils.httpGet(url + "/apply/getMatchApplyDayList.do" + params); List<User> userList = GsonUtils.parseJsonArrayWithGson(str, User.class); return userList; } //-----------------------------測試---------------------------------------------- /** * 若是有參數參考上面,已測,post方法和get同樣, * 具體能夠參照 get. * * @param idNumber * @return */ //json格式轉對象 @Override public MatchDay getMatchDay(String idNumber) { String str = HttpRequestUtils.httpGet(url + "/apply/getMatchApplyDay.do"); MatchDay matchDay = GsonUtils.parseJsonWithGson(str, MatchDay.class); return matchDay; } //json格式數組能夠用JsonObject接收 @Override public MatchDayModel getMatchDayList(String idNumber) { String str = HttpRequestUtils.httpGet(url + "/apply/getMatchApplyDayListJson.do"); MatchDayModel matchDayModel = GsonUtils.parseJsonWithGson(str, MatchDayModel.class); return matchDayModel; } //json格式數組能夠用JsonArrayt接收 @Override public List<MatchDay> getMatchDayListArray(String idNumber) { String str = HttpRequestUtils.httpGet(url + "/apply/getMatchApplyDayListJsonArray.do"); List<MatchDay> matchDays = GsonUtils.parseJsonArrayWithGson(str, MatchDay.class); return matchDays; } }
測試:apache
package com.example.demo.controller; import com.example.demo.entity.MatchDay; import com.example.demo.model.MatchDayModel; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by ningcs on 2017/7/26. */ @RestController public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/getMatchDay",method = {RequestMethod.POST,RequestMethod.GET}) public MatchDay getMatchDay(String idNumber){ return userService.getMatchDay(idNumber); } @RequestMapping(value = "/getMatchDayList",method = {RequestMethod.POST,RequestMethod.GET}) public MatchDayModel getMatchDayList(String idNumber){ return userService.getMatchDayList(idNumber); } @RequestMapping(value = "/getMatchDayListArray",method = {RequestMethod.POST,RequestMethod.GET}) public List<MatchDay> getUserList(String idNumber){ return userService.getMatchDayListArray(idNumber); } }
測試提供:json
package com.example.demo.controller; import com.example.demo.entity.MatchDay; import com.example.demo.model.MatchDayModel; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * Created by ningcs on 2017/7/26. * */ @RestController @RequestMapping("apply") public class HttpProvider { /** * * list 放在對象裏面 * * @return */ @RequestMapping(value = "/getMatchApplyDay", method = {RequestMethod.GET,RequestMethod.POST}) public JSONObject getMatchApplyDay() { JSONObject jsonObject =new JSONObject(); MatchDay matchDay =new MatchDay(); matchDay.setDayInfo("2016"); matchDay.setDayInfoDetail("2016-09"); matchDay.setStatus(1); matchDay.setId(1); return jsonObject.fromObject(matchDay); } /** * * list 放在對象裏面 * * @return */ @RequestMapping(value = "/getMatchApplyDayListJson", method = {RequestMethod.GET,RequestMethod.POST}) public JSONObject getMatchApplyDayListJson() { JSONObject jsonObject =new JSONObject(); MatchDayModel matchDayModel =new MatchDayModel(); List<MatchDay> matchDays =new ArrayList<>(); MatchDay matchDay =new MatchDay(); matchDay.setDayInfo("2016"); matchDay.setDayInfoDetail("2016-09"); matchDay.setStatus(1); matchDay.setId(1); matchDays.add(matchDay); matchDayModel.setMatchDays(matchDays); return jsonObject.fromObject(matchDayModel); } /** * * 用JsonArray返回 * @return */ @RequestMapping(value = "/getMatchApplyDayListJsonArray", method = {RequestMethod.GET,RequestMethod.POST}) public JSONArray getMatchApplyDayListJsonArray() { JSONArray jsonArray =new JSONArray(); List<MatchDay> matchDays =new ArrayList<>(); MatchDay matchDay =new MatchDay(); matchDay.setDayInfo("2016"); matchDay.setDayInfoDetail("2016-09"); matchDay.setStatus(1); matchDay.setId(1); matchDays.add(matchDay); return jsonArray.fromObject(matchDays); } }
配置文件:數組
get_user_ip=http://localhost:7073/ server.port=7073
詳細運行結果:服務器
hithub地址:app
https://github.com/ningcs/SpringBootHttpClient