JAVA HttpClient使用

为达到以下目的:

  • 要发送的参数json和platformKey, 以post方式传送,
  • 对参数进行Encode,只针对参数的值进行encode,否则解析不了;


引用的包

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


maven依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>

        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>




第一种形式——直接构造byte数组:

private String postTo1(String content) {

            HttpClient client = HttpClientBuilder.create()
                    .build();
            HttpPost request = new HttpPost(hetuUrl);
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(10000)
                    .setConnectTimeout(50000)
                    .setSocketTimeout(50000)
                    .build();
            request.setConfig(config);
            request.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            try {
                String body = "json=" + URLEncoder.encode(content, "UTF-8")
                        + "&platformKey=" + platformKey;
                String encodedBody = body;
                byte[] bytes = encodedBody.getBytes("UTF-8");
                request.setEntity(new ByteArrayEntity(bytes));
                HttpResponse response = client.execute(request);

                HttpEntity entity = response.getEntity();

                byte[] result = new byte[(int) entity.getContentLength()];

                entity.getContent().read(result);

                String s = new String(result);

                return s;

            } catch (Throwable e) {
                logger.error(ExceptionUtils.getStackTrace(e));
            }

            return "{}";
        }

第二种形式——使用UrlEncodedFormEntity:

private String pushToHeTu(String content) {

            HttpClient client = HttpClientBuilder.create()
                    .build();
            HttpPost request = new HttpPost(hetuUrl);
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(10000)
                    .setConnectTimeout(50000)
                    .setSocketTimeout(50000)
                    .build();
            request.setConfig(config);
            request.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            try {
                List<NameValuePair> pairs = new ArrayList<>();
                pairs.add(new BasicNameValuePair("json", content));
                pairs.add(new BasicNameValuePair("platformKey", platformKey));
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                request.setEntity(formEntity);
                HttpResponse response = client.execute(request);

                HttpEntity entity = response.getEntity();

                byte[] result = new byte[(int) entity.getContentLength()];

                entity.getContent().read(result);

                String s = new String(result);

                return s;

            } catch (Throwable e) {
                logger.error(ExceptionUtils.getStackTrace(e));
            }

            return "{}";
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值