HttpClient 以及使用 gson 解析json

HttpClient

HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

工具类:

 httpPost:

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:

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:

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;
    }


}

 

 

测试:

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);
    }

}

 

 

 

测试提供:

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地址:

https://github.com/ningcs/SpringBootHttpClient

 

 

转载于:https://my.oschina.net/u/2851681/blog/1489782

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值