美文网首页
java 利用http的post方法发送json对象

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

作者: DuffyMagic | 来源:发表于2019-01-10 09:35 被阅读0次
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依赖即可

相关文章

网友评论

      本文标题:java 利用http的post方法发送json对象

      本文链接:https://www.haomeiwen.com/subject/mzjorqtx.html