HttpClient4 使用简介

http://hc.apache.org/httpcomponents-client/

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();

你可能感兴趣的:(apache,socket,Google,F#)