httpclient post推送数据

java

浏览数:1,202

2019-1-12

片段 1片段 2片段 3


客户端代码

 /**
     * 从接口获取数据
     * @param url 服务器接口地址
     * @param json 传入的参数 若获取全部,此项为空
     * @return 返回查询到的数据
     * @throws HttpException
     * @throws IOException
     */
    public JSONObject post(String url, String json) throws HttpException, IOException{
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();

            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
            StringEntity se = new StringEntity(json, Charset.forName("UTF-8"));
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);

            if (response != null && response.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject resultJsonObject = JSONObject.parseObject(result);
                return resultJsonObject;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


测试方法

//本地tomcat
//    private  String url = "http://127.0.0.1:8080/Car4s-1.0-SNAPSHOT/carApi/getCarAll";//获取全部数据
//    private  String url = "http://127.0.0.1:8080/Car4s-1.0-SNAPSHOT/carApi/getCar";//获取某一条记录
//    private String url = "http://127.0.0.1:8080/Car4s-1.0-SNAPSHOT/carApi/postCarList";//推送数据

@Test
    public void testPostList() throws IOException, HttpException {

        JSONArray jsonArray = new JSONArray();
        //批量推送数据
        for (int i = 1; i < 3; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("carType", "测试00"+i);
            //Integer modifyType 1增加 2更新
            jsonObject.put("modifyType", new Integer(1));
            jsonArray.add(jsonObject);
        }

        //推送一条数据
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("carSize", 4);
//        jsonObject.put("carType", "测试3");
//        jsonObject.put("keepRequirement", "无");
//        jsonObject.put("keepTitle", "无");
//        jsonObject.put("keepPrice", 80.0);
//        jsonObject.put("repairePrice", 80.0);
//        jsonObject.put("modifyType", new Integer(1));
//        jsonArray.add(jsonObject);

        String string = JSONArray.toJSONString(jsonArray);
        JSONObject post = post(url, string);
        System.out.println(post);
    }


服务器方法

/**
     * 推送接口,支持一条或者多条数据
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/postCarList")
    @ResponseBody
    public JSONObject postCarList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject jsonObject = new JSONObject();
        request.setCharacterEncoding("UTF-8");
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
        String jsonStr = null;
        StringBuilder result = new StringBuilder();
        try {
            while ((jsonStr = reader.readLine()) != null){
                result.append(jsonStr);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        reader.close();

        JSONArray jsonArray = JSONArray.parseArray(result.toString());
        try {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject o = (JSONObject) jsonArray.get(i);
                Car car = new Car();
                car.setCarType(o.getString("carType"));
                car.setLastTime(DateUtils.stringTodate(o.getString("lastTime"), null));
                car.setCarSize(o.getInteger("carSize"));
                car.setKeepRequirement(o.getString("carType"));
                car.setKeepTitle(o.getString("keepTitle"));
                car.setKeepPrice(o.getDouble("keepPrice"));
                car.setRepairePrice(o.getDouble("repairePrice"));
                if (o.getInteger("modifyType") == null){
                    jsonObject.put("msg", "Post失败,未指定修改类型");
                    jsonObject.put("code", -1);
                    return jsonObject;
                }
                int modifyType = o.getInteger("modifyType");
                //增加
                if (modifyType == 1){
                    carService.save(car);
                }
                //更新
                else if (modifyType == 2){
                    car.setCarId(o.getInteger("carId"));
                    carService.update(car);
                }else {
                    jsonObject.put("msg", "Post失败,修改类型指定类型错误");
                    jsonObject.put("code", -1);
                    return jsonObject;
                }
            }
            jsonObject.put("msg", "Post成功");
            jsonObject.put("code", 1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }