HttpClient4 使用简介

[url]http://hc.apache.org/httpcomponents-client/[/url]

lib:
apache-mime4j-0.6.jar
commons-codec-1.3.jar
commons-logging-1.1.1.jar
httpclient-4.0.2.jar
httpcore-4.0.1.jar
httpmime-4.0.2.jar

一个简单的Demo,包含proxy, authentication, post entity, 属性设置。

HttpClient client = new DefaultHttpClient();

// set proxy
HttpHost proxy = new HttpHost("someproxy", 8080);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "user_agent");

// set authentication
((DefaultHttpClient)client).getCredentialsProvider().setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password"));

// set formated url
// List<NameValuePair> qparams = new ArrayList<NameValuePair>();
// qparams.add(new BasicNameValuePair("q", "httpclient"));
// qparams.add(new BasicNameValuePair("btnG", "Google Search"));
// qparams.add(new BasicNameValuePair("aq", "f"));
// qparams.add(new BasicNameValuePair("oq", null));
// URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", URLEncodedUtils.format(qparams, "UTF-8"), null);
// HttpGet get = new HttpGet(uri);

HttpPost post = new HttpPost("http://localhost/");

// determines the timeout in milliseconds until a connection is established.
post.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);
// defines the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets).
post.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000L);

// set post method entity
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
Header[] headers = response.getAllHeaders();
HttpEntity entity = response.getEntity();
System.out.println(entity.getContentType());
System.out.println(entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
entity.consumeContent();
client.getConnectionManager().shutdown();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值