zoukankan      html  css  js  c++  java
  • Java发送http请求发送json对象

    直接上代码:

    此工具类,无法获取到500之类的错误信息,返回200时候才有result,可以参考 另一篇:

     《 Java发送Http带HEADER参数》 https://www.cnblogs.com/coloz/p/13031148.html  

      http工具类:

    public static String httpPostWithjson(String url, String json) throws IOException {
    String result = "";
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
    BasicResponseHandler handler = new BasicResponseHandler();
    StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    result = httpClient.execute(httpPost, handler);
    return result;
    } catch (Exception e) {
    e.printStackTrace();

    } finally {
    try {
    httpClient.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    return result;
    }

    测试:
    String httpURL = "http://localhost:8080/xxxxxx/orgnameRentArea/save.do";
    try {
    OrgnameRentArea rentArea = new OrgnameRentArea();
    rentArea.setProjectId("1");
    rentArea.setRegularrentName("1");
    BigDecimal bigDecimal = new BigDecimal(2);
    rentArea.setRegularuseArea(bigDecimal);
    rentArea.setTempraturEarea(1);
    rentArea.setIsflag(1);
    rentArea.setStartTime("1");
    JSONObject jsonObject = JSONObject.fromObject(rentArea);
    String result1 = httpPostWithjson(httpURL, jsonObject.toString());
    } catch (IOException e) {
    e.printStackTrace();
    }


    后端接收方式:
    @RequestBody 这个注解不能少
    @RequestMapping("/save")
    @ResponseBody
    public Map<String, Object> save(HttpServletRequest request, @RequestBody OrgnameRentArea model ) {

    return orgnameRentAreaService.save(request, model);
    }
    DEBUG视图:




  • 相关阅读:
    IIS中ASP.NET安全配置
    好用的SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面)
    js取两位小数点
    json格式的ajax传输交互
    js全选与反选
    formdata,ajax提交数据
    js判断是否微信浏览器、IE浏览器
    js实现列表从下往上循环滚动
    绝对定位始终居中
    存储、字符串截取、两端对齐、样式绑定、微信调拨号功能
  • 原文地址:https://www.cnblogs.com/coloz/p/10619826.html
Copyright © 2011-2022 走看看