• HttPclient 以post方式发送json


    使用HttpClient 以POST的形式发送json字符串 
    步骤: 
    1.url 、parameters 
    2.创建httpClient对象 
    3.创建HttpPost对象 
    4.为post对象设置参数 
    5.将参数以实体的实行放入post对象中 
    6.client.execute(post);返回response对象 
    7.通过response对象获取响应码, 
    8.获得结果实体 

    Java代码  收藏代码
      1. public void HttpClientPostByJson(){  
      2.         String url = "http://localhost:8080/../../";  
      3.         String param = "{"endTxnDate":"20151114","merchId":"","sendTime":"201510132012123","startTxnDate":"20151111"}";  
      4.                 //创建client和post对象  
      5.         HttpClient client = HttpClients.createDefault();  
      6.         HttpPost post = new HttpPost(url);  
      7.         //json形式  
      8.         post.addHeader("content-type", "application/json;charset=utf-8");  
      9.         post.addHeader("accept","application/json");  
      10.         //json字符串以实体的实行放到post中  
      11.         post.setEntity(new StringEntity(param,Charset.forName("utf-8")));  
      12.         HttpResponse response = null;  
      13.         try {  
      14.                         //获得response对象  
      15.             response = client.execute(post);  
      16.         } catch (Exception e) {  
      17.             e.printStackTrace();  
      18.         }   
      19.           
      20.         if(HttpStatus.SC_OK!=response.getStatusLine().getStatusCode()){  
      21.             System.out.println("请求返回不正确");  
      22.         }  
      23.           
      24.         String result="";  
      25.         try {  
      26.                         //获得字符串形式的结果  
      27.             result = EntityUtils.toString(response.getEntity());  
      28.         } catch (Exception e) {  
      29.             e.printStackTrace();  
      30.         }   
      31.         System.out.println(result);  
      32.           
      33.     }  
  • 相关阅读:
    B. Xor of 3 题解(思维+构造)
    小 L 与 GCD 题解(数学 hard)
    F. Clear The Matrix 题解(状压dp)
    小顶堆与大顶堆的自定义cmp函数
    字符指针、字符数组
    python中创建dict对象
    中缀表达式转后缀表达式
    vue中keep-alive,include的缓存问题
    vue 冒号 :、@、# 是什么意思? v-bind v-on v-slot v-是指令
    vue 自定义指令 v-
  • 原文地址:https://www.cnblogs.com/muhy/p/10401241.html
Copyright © 2020-2023  润新知