- httpClient 最本质的功能是 执行 http 方法。
- httpClient 参考文档地址:(http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e43)
- 测试代码 github 下载地址:(https://github.com/xiaoyugelicai/TestJackson.git)
- 具体示例代码如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<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));
nameValuePairs.add(new BasicNameValuePair("validate", md5sign(data + partnerId + password)));
HttpPost httpPost = new HttpPost("url");
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
httpPost.setEntity(urlEncodedFormEntity);
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[] = {
'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];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = abyte0[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
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);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
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();
}
}