httpclient 以及 urlConnection 发送请求

本文介绍如何使用Apache HttpClient库执行HTTP POST请求。示例代码展示了两种方式:一种是通过键值对传递数据,另一种是直接传递字符串数据。此外,还介绍了如何配置连接超时和读取超时。
  1. httpClient 最本质的功能是 执行 http 方法。
  2. httpClient 参考文档地址:(http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e43)
  3. 测试代码 github 下载地址:(https://github.com/xiaoyugelicai/TestJackson.git)
  4. 具体示例代码如下:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.5</version>
        </dependency>
package testJackson;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

/**
 * 测试 httpClient post相关方法
 * @author hualei
 * @date May 3, 2017 11:10:15 AM
 * 
 */
public class TestHttpClient {

    /**
     * 传递 键值对 数据
     * @throws ClientProtocolException
     * @throws IOException
     */
    @Test
    public void postNameValuePairData() throws ClientProtocolException, IOException{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String data = "data";
        String partnerId = "partnerId";
        String password = "password";

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("version", "1.0"));
        nameValuePairs.add(new BasicNameValuePair("partnerId", partnerId));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        nameValuePairs.add(new BasicNameValuePair("xmldata", data));
        // validate 为 data + partner + password 进行 md5 加密后的结果
        nameValuePairs.add(new BasicNameValuePair("validate", md5sign(data + partnerId + password)));

        HttpPost httpPost = new HttpPost("url");
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
        httpPost.setEntity(urlEncodedFormEntity);

        // 通过 requestConfig 配置连接超时和socket超时
        // 连接超时指 网络与服务器建立连接 超时时间
        // socket超时指 读数据 超时时间,也就是从 服务器获取响应数据需要等待的时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
        httpPost.setConfig(requestConfig);

        // 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        HttpEntity entity = response.getEntity();
        if(entity != null){
            System.out.println(EntityUtils.toString(entity, "utf-8"));
        }
    }

    /**
     * 传递 值 数据
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    @Test
    public void postValueData() throws ClientProtocolException, IOException{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String data = "data";

        HttpPost httpPost = new HttpPost("url");
        StringEntity stringEntity = new StringEntity(data, "utf-8");
        httpPost.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        if(entity != null){
            System.out.println(EntityUtils.toString(entity));
        }
    }

    public static char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static String md5sign(String data) {
        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            messagedigest.reset();
            messagedigest.update(data.getBytes("UTF8"));
            byte abyte0[] = messagedigest.digest();
            char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
            // 所以表示成 16 进制需要 32 个字符
            int k = 0; // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = abyte0[i]; // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
                // >>> 为逻辑右移,将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获得密文时出错!");
        }
    }

}
/**
     * 通过 URLConnection 发送请求
     * @throws IOException
     */
    public void testPost() throws IOException {
        URL url= new URL("https://www.google.com");
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();   


        // //设置连接属性   
        httpConn.setDoOutput(true);// 使用 URL 连接进行输出   
        httpConn.setDoInput(true);// 使用 URL 连接进行输入   
        httpConn.setUseCaches(false);// 忽略缓存   
        httpConn.setRequestMethod("POST");// 设置URL请求方法   
        String requestString = "客服端要以以流方式发送到服务端的数据...";   


        // 设置请求属性   
        // 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致   
        byte[] requestStringBytes = requestString.getBytes("utf-8");   
        httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);   
        httpConn.setRequestProperty("Content-Type", "application/octet-stream");   
        httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接   
        httpConn.setRequestProperty("Charset", "UTF-8");   

        // 建立输出流,并写入数据   
        OutputStream outputStream = httpConn.getOutputStream();   
        outputStream.write(requestStringBytes);   
        outputStream.close();   
        // 获得响应状态   
        int responseCode = httpConn.getResponseCode();   
        PrintUtil.print("response code", responseCode);
        if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功   
        // 当正确响应时处理数据   
        StringBuffer sb = new StringBuffer();   
        String readLine;   
        BufferedReader responseReader;   
        // 处理响应流,必须与服务器响应流输出的编码一致   
         responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));   
        while ((readLine = responseReader.readLine()) != null) {   
            sb.append(readLine).append("\n");   
        }   
        responseReader.close();   

        } 
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值