HttpClient

  • HttpClient 4.1 以后不再在Apache Commons下,而是位于Apache HttpComponents

org.apache.commons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别:
Commons的HttpClient项目现在是生命的尽头,不再被开发,已被Apache HttpComponents项目HttpClient和的HttpCore
模组取代,提供更好的性能和更大的灵活性。

	public final static void main(String[] args) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpGet httpget = new HttpGet("http://httpbin.org/get");

			System.out.println("Executing request " + httpget.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());

				// Get hold of the response entity
				HttpEntity entity = response.getEntity();

				// If the response does not enclose an entity, there is no need
				// to bother about connection release
				if (entity != null) {
					InputStream instream = entity.getContent();
					try {
						instream.read();
						// do something useful with the response

						byte[] bytes = new byte[0];
						bytes = new byte[instream.available()];
						instream.read(bytes);
						String str = new String(bytes);
						System.out.println("str: " + str);

						String string = EntityUtils.toString(entity, "UTF-8");
						System.out.println("string: " + string);
					} catch (IOException ex) {
						// In case of an IOException the connection will be released
						// back to the connection manager automatically
						throw ex;
					} finally {
						// Closing the input stream will trigger connection release
						instream.close();
					}
				}
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}
  • 最简单post请求
	public static void main(String[] args) throws Exception {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("account", ""));
		formparams.add(new BasicNameValuePair("password", ""));
		HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)// 一、连接超时:connectionTimeout-->指的是连接一个url的连接等待时间
				.setSocketTimeout(5000)// 二、读取数据超时:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间
				.setConnectionRequestTimeout(5000).build();

		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost("http://cnivi.com.cn/login");
		post.setEntity(reqEntity);
		post.setConfig(requestConfig);
		HttpResponse response = client.execute(post);

		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity resEntity = response.getEntity();
			String message = EntityUtils.toString(resEntity, "UTF-8");
			System.out.println(message);
		} else {
			System.out.println("请求失败");
		}
	}
  • 解决参数乱码问题
HttpEntity entity = new StringEntity(xml, ContentType.create("text/xml", Consts.UTF_8));

参考资料

posted @ 2018-06-26 17:31  流星<。)#)))≦  阅读(135)  评论(0编辑  收藏  举报