Java代码实现post请求,如:curl -X POST -H “Content-Type: applicationjson“https:xxxxx.cnxxxx-d ‘{

Java代码实现post请求,如:curl -X POST -H “Content-Type: applicationjson“https:xxxxx.cnxxxx-d ‘{,第1张

Java代码实现post请求,如:curl -X POST -H “Content-Type: application/json“ https://xxxxx.cn/xx/xx -d ‘{ 需求

将一个请求转换为java代码去执行,想要执行的命令格式如下:

curl -X POST -H "Content-Type: application/json"  
https://xxxxx.cn/xx/xx 
-d '{
  "msg_type":"text",
  "content":{
    "text":"request example"
    }
}'
代码实现
 	
    public void httpPost(String url,String str) throws IOException {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        PostMethod method = new PostMethod(url);
        RequestEntity entity = new StringRequestEntity(str,"application/json","UTF-8");
        method.setRequestEntity(entity);
        httpClient.executeMethod(method);
        InputStream in = method.getResponseBodyAsStream();
//下面将stream转换为String
        StringBuffer sb = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(in, "UTF-8");
        char[] b = new char[4096];
        for(int n; (n = isr.read(b)) != -1;) {
            sb.append(new String(b, 0, n));
        }
        String returnStr = sb.toString();
        System.out.println(returnStr);
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5686303.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存