Java代码发送POST请求

首先写一个方法,用于接收POST请求

public static String httpPost(String url, List<NameValuePair> list) {
        log.info("the request info for url = {} is: {}", url);

        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = getDefaultHttpClient();
        // 创建HttpPost
        HttpPost httppost = new HttpPost(url);
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            httppost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httppost);

            HttpEntity respEntity = response.getEntity();

            if (null != respEntity) {
                String result = EntityUtils.toString(respEntity, "UTF-8");
                log.info("the response info for url = {}  is: {}", url, result);

                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.info("exception: ", e);
        }

        return "";
    }

/**
     * 获取传输普通http请求的HttpClient
     */
    private static CloseableHttpClient initHttpClient() {
        DnsResolver dnsResolver = new SystemDefaultDnsResolver();
//        DnsResolver dnsResolver = getDnsResolver();
        //需要通过以下代码声明对https连接支持
        SSLContext sslcontext = null;
        HttpClientBuilder httpClientBuilder = null;
        CloseableHttpClient httpClient = null;

        try {
            sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                    new TrustSelfSignedStrategy())
                    .build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }


        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

        if (null != sslcontext) {
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext, hostnameVerifier);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslsf)
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry, dnsResolver);
            connManager.setMaxTotal(100);
            connManager.setDefaultMaxPerRoute(10);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50 * 1000).setConnectTimeout(30 * 1000).build();

            httpClientBuilder = HttpClients.custom();
            httpClientBuilder.setConnectionTimeToLive(60L, TimeUnit.SECONDS);
            httpClientBuilder.setConnectionManager(connManager);
            httpClientBuilder.setDefaultRequestConfig(requestConfig);

            httpClient = httpClientBuilder.build();
        }

        return httpClient;
    }

调用上述POST方法的代码如下:

List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("param1", "value1"));
list.add(new BasicNameValuePair("param2", "value2"));
String result = HttpUtilsForAdd.httpPost("http://beta83.baike.sogou.com/zyg/matchLemmaByTitle.v", list);


Java发送POST请求,我们可以通过引入Apache HttpClient库来实现。下面是引入依赖的代码: 首先,在pom.xml文件中添加以下依赖项: ```xml <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> </dependencies> ``` 接下来,我们可以编写Java代码发送POST请求。以下是一个简单的示例: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class Main { public static void main(String[] args) { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost请求 HttpPost httpPost = new HttpPost("http://example.com/post-endpoint"); // 设置POST请求的内容 String requestBody = "This is the request body"; StringEntity stringEntity = new StringEntity(requestBody, "utf-8"); httpPost.setEntity(stringEntity); // 发送POST请求并获取响应 try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); // 处理响应 System.out.println("Response status code: " + httpResponse.getStatusLine().getStatusCode()); System.out.println("Response body: " + responseBody); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例代码中,我们创建了一个HttpClient实例,并使用HttpPost对象来设置POST请求的URL和内容。然后,我们使用HttpClient的execute方法发送请求,并通过HttpResponse对象获取响应内容。 注意,这只是一个简单的示例,实际中可能会涉及更多的设置和处理。 希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值