httpclient 以及 urlConnection 发送请求
来源:互联网 发布:windows arping 编辑:程序博客网 时间:2024/06/06 21:55
- httpClient 最本质的功能是 执行 http 方法。
- httpClient 参考文档地址:(http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e43)
- 测试代码 github 下载地址:(https://github.com/xiaoyugelicai/TestJackson.git)
- 具体示例代码如下:
<!-- 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(); } }
0 0
- httpclient 以及 urlConnection 发送请求
- URLConnection发送http请求
- HttpClient发送http请求以及上传文件
- HTTP URLConnection 发送get请求
- 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL
- 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL
- Httpclient发送POST请求
- HttpClient发送请求
- httpClient发送post请求
- httpCLient 发送请求
- HttpClient发送url请求
- HttpClient发送Request请求
- httpclient发送put请求
- HTTPClient 发送HTTPS请求
- httpClient 发送 http请求
- httpClient发送请求
- HttpClient发送网络请求
- HttpClient发送后台请求
- python——接收处理外带的参数
- 图论学习(二)在Boost Graph中返回连通子图序列
- 【学习笔记07】java面向对象-继承
- mysqld --initialize 执行失败
- Java字符串去除中文
- httpclient 以及 urlConnection 发送请求
- 磁疗是真的吗?磁刺激技术在神经疾病方面的研究与应用
- Java方向如何准备BAT技术面试答案(汇总版)
- XMind 8中怎样设置自动保存/备份?
- intelj idea 创建 Servlet 类
- C++第4回作业
- Android 开机动画客制化
- java 小数位数保留的几种方法
- [程序员面试金典-查找-]找出字符串