java Httpclient发送get和post以及使用代理服务器
使用代理服务器
package com.jhz.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
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 java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProxySelector {
final static String proxyHost = "XXXX";
final static Integer proxyPort = 0;
public static final String filePath = "F:\\Java\\Java-project\\Advanced-Framework\\homework\\src\\main\\resources\\index.htm";
private static HttpHost proxy = null;
private static RequestConfig reqConfig = null;
static {
proxy = new HttpHost(proxyHost, proxyPort, "http");
reqConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(10000)
.setSocketTimeout(10000)
.setExpectContinueEnabled(false).setProxy(new HttpHost(proxyHost, proxyPort))
.setCircularRedirectsAllowed(true)
.build();
}
public static void main(String[] args) {
doGetRequest();
}
public static void doGetRequest() {
String targetUrl = "http://aajy.net/";
try {
Map<String, String> urlParams = new HashMap<>();
urlParams.put("uid", "1234567");
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramsAdapter(urlParams), "UTF-8"));
HttpGet httpGet = new HttpGet(targetUrl + "?" + paramStr);
String result = doRequest(httpGet);
writeFile(result);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void writeFile(String result) {
FileWriter out = null;
try {
out = new FileWriter(filePath);
out.write(result);
out.flush();
System.out.println("写入成功!");
} catch(IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
public static void doPostRequest() {
try {
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
Map<String, String> formParams = new HashMap<>();
formParams.put("uid", "1234567");
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(paramsAdapter(formParams), "utf-8");
httpPost.setEntity(uefEntity);
String result = doRequest(httpPost);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setHeaders(HttpRequestBase httpReq) {
httpReq.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36");
httpReq.addHeader("xxx", "xxx");
}
public static String doRequest(HttpRequestBase httpReq) {
String result = new String();
httpReq.setConfig(reqConfig);
try {
setHeaders(httpReq);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResp = httpClient.execute(httpReq);
int statusCode = httpResp.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = httpResp.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
httpResp.close();
httpClient.close();
httpReq.abort();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return result;
}
private static List<NameValuePair> paramsAdapter(Map<String, String> map) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return nvps;
}
}
发送get请求
package com.jhz.httpclient;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class SendGetRequest {
private static String url = "https://baike.baidu.com/search/word?word=HTTP";
public static void main(String args[]) throws Exception {
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
System.out.println("调用URL: " + httpGet.getURI());
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
System.out.println("状态码:" + response.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
StringBuffer responseSB = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseSB.append(line);
}
System.out.println("响应头:" + Arrays.toString(response.getAllHeaders()));
System.out.println("响应体:" + responseSB);
reader.close();
httpClient.close();
}
}
发送post请求
package com.jhz.httpclient;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
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.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Arrays;
public class SendPostRequest {
public static void main(String[] args) {
System.out.println(sendPost("https://baike.baidu.com", JSON.toJSONString("work=HTTP")));
}
public static String sendPost(String url, String data){
String body = "";
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity s = new StringEntity(data, "utf-8");
s.setContentEncoding(new BasicHeader("contentType",
"application/json"));
httpPost.setEntity(s);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, "UTF-8");
System.out.println("状态码:" + response.getStatusLine().getStatusCode());
System.out.println("响应头:" + Arrays.toString(response.getAllHeaders()));
System.out.println("响应体:" + body);
}
EntityUtils.consume(entity);
response.close();
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
}
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jhz</groupId>
<artifactId>homework</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>11.0.9</version>
</dependency>
<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>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
</project>
|