赞
踩
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依赖即可
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。