当前位置:   article > 正文

java post json_java 利用http的post方法发送json对象

java post json_java 利用http的post方法发送json对象

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.util.EntityUtils;

public class HttpClient {

public static void main(String args[]){

JSONObject jsondata=new JSONObject();

jsondata.put("docid","gns://54BB581FE79941A6B7BDE4D9AD960EB6");

jsondata.put("name","httpcreate");

doPost("http://192.168.184.165:9123/v1/dir?method=create&userid=a4b3cc90-0a50-11e9-b2ad-005056b07256&tokenid=a8bedff6-f1b7-4cd3-851f-c9b2fa624cfe",jsondata);

}

public static JSONObject doPost(String url, JSONObject json){

CloseableHttpClient httpclient = HttpClientBuilder.create().build();

HttpPost post = new HttpPost(url);

JSONObject response = null;

try {

StringEntity s = new StringEntity(json.toString());

s.setContentEncoding("UTF-8");

s.setContentType("application/json");//发送json数据需要设置contentType

post.setEntity(s);

HttpResponse res = httpclient.execute(post);

if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

String result = EntityUtils.toString(res.getEntity());// 返回json格式:

response = JSONObject.fromObject(result);

}

} catch (Exception e) {

throw new RuntimeException(e);

}

System.out.println(response);

return response;

}

}

报错导入maven依赖即可

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/302850
推荐阅读
相关标签
  

闽ICP备14008679号