`

HttpClient请求

    博客分类:
  • java
阅读更多

一个apache的httpclient简单范本,常用在WebService调用

public void httpInvoke(String url) throws HttpException, IOException {
		HttpClient client = new HttpClient();
		client.getParams().setContentCharset("utf-8");
		client.getParams().setParameter("http.protocol.content-charset", "utf-8");
		client.getParams().setSoTimeout(5000);
		//使用代理
		client.getHostConfiguration().setProxy("192.168.199.251", 3128);//IP和port
		client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("userName", "password"));

		PostMethod method = new PostMethod(url);
		//直接设置参数
//		method.addParameter("param1", "value1");
		//使用NameValuePair设置参数
//		NameValuePair pair = new NameValuePair("param1", "value1");
//		method.addParameter(pair);
		//设置请求内容
//		NameValuePair[] pairs = new NameValuePair[]{new NameValuePair("name", "value")};
//		method.setRequestBody(pairs);

		client.executeMethod(method);
		if (method.getStatusCode() == HttpStatus.SC_OK) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		}
		method.releaseConnection();
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics