HttpClient使用详解 HttpGet HttpPost 超时设置
- 2016-04-07 22:33:00
- admin
- 原创 3395
一、maven配置httpclient
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
</dependencies>
二、示例代码
代码下载:HttpTest.java
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.*;
import org.apache.http.impl.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.message.*;
import org.apache.http.util.*;
import java.util.*;
public class HttpTest {
//打印http响应头
public static void printHeaders(HttpResponse response) {System.out.println(response.getStatusLine().getStatusCode());
Header[] headers = response.getAllHeaders();
for (Header header: headers) {
System.out.print(header.getName() + ": ");
System.out.println(header.getValue());
}
}
//打印http响应内容
public static void printContent(HttpResponse response) throws Exception {HttpEntity entity = response.getEntity();
System.out.println("length: " + entity.getContentLength());
String content = EntityUtils.toString(entity, "UTF-8");
System.out.println("content: ".concat(content));
}
//测试http的get
public static void testGET() throws Exception {HttpClient client = HttpClients.createDefault();
String url = "http://211.149.156.144:8080/springmvc/test_get.do?name=feinen";
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
printHeaders(response);
printContent(response);
}
//测试http的post
public static void testPOST() throws Exception {HttpClient client = HttpClients.createDefault();
String url = "http://211.149.156.144:8080/springmvc/test_post.do";
HttpPost request = new HttpPost(url);
ArrayList<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "feinen"));
// StringEntity is used for string.
UrlEncodedFormEntity uefEntity =
new UrlEncodedFormEntity(formParams, "UTF-8");
request.setEntity(uefEntity);
HttpResponse response = client.execute(request);
printHeaders(response);
printContent(response);
}
//程序主方法
public static void main(String[] args) throws Exception {testGET();
System.out.println("#######################");
testPOST();
}
}
三、超时设置
public static void configHttpRequest(HttpRequestBase request) {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(100) //连接超时
.setSocketTimeout(100) //读超时
.build();
request.setConfig(config);
}
发表评论