用httpclient发送post请求


import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by caiyl on 2017/11/14.
 */
public class TestApp {

    public static String sendPostWithJson(String url, String json, String chart) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, "utf-8");
        entity.setContentEncoding(chart);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        String responseStr = null;

        try {
            response = httpclient.execute(httpPost);
            responseStr = EntityUtils.toString(response.getEntity());
        } catch (IOException var17) {
            var17.printStackTrace();
        } finally {
            try {
                response.close();
                httpclient.close();
            } catch (IOException var16) {
                var16.printStackTrace();
            }

        }

        return responseStr;
    }

    public static void main(String[] args) {
        String url = "http://wgetwinddt.lovingfox.cn:10700/cuccwifi/add";
        String data = "{\"tphone\":\"14112344321\",\"termip\":\"10.25.40.3\",\"termac\":\"192.168.20.31\",\"online\":\"2017-09-28 08:09:02\",\"brchno\":\"中文测试\"}";
        String responseContent = sendPostWithJson(url, data, "UTF-8");
        System.out.println(responseContent);
    }
}

主要引入httpclient-4.3.6-4.3.6.jar与httpcore-4.4-4.4.jar即可。

你可能感兴趣的:(用httpclient发送post请求)