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