使用HttpClient实现Http通信

一、建立工程,工程结构和导入的jar包如下图所示:


二、代码片段

1、HttpUtil.java

package http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

/**
 * HTTP通信工具类
 * @author 丑哥最风骚
 * @date 2014-02-20
 */
public class HttpUtil {
	private static final int CONNECTIONTIMEOUT = 20000;
	private static final int SOTIMEOUT = 60000;
	
	/**
	 * 以GET方式访问
	 * @param url		指定的url(可接参数)
	 * @return			服务器的返回结果
	 */
	public static String doGet(String url) {
		HttpResponse httpResponse = null;
		HttpParams httpParameters = new BasicHttpParams();
		HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
		HttpConnectionParams.setStaleCheckingEnabled(httpParameters, false);
		HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTIONTIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParameters, SOTIMEOUT);
		HttpConnectionParams.setSocketBufferSize(httpParameters, 1024);
		HttpClientParams.setRedirecting(httpParameters, false);
		HttpClient httpclient = new DefaultHttpClient(httpParameters);

		HttpGet httpRequest = new HttpGet(url);
		String result = "";
		try {
			httpResponse = httpclient.execute(httpRequest);
			if (null != httpResponse) {
				int resCode = httpResponse.getStatusLine().getStatusCode(); // 返回码
				if (resCode == 200) {	// 网络响应成功
					result = EntityUtils.toString(httpResponse.getEntity());
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();
		return result;
	}
	
	/**
	 * 以POST方式访问
	 * @param url		指定的url(不接参数)
	 * @param params	由传递参数和值组成的键值对
	 * @return			服务器的返回结果
	 */
	public static String doPost(String url, List<NameValuePair> params) {
		HttpResponse httpResponse = null;
		HttpParams httpParameters = new BasicHttpParams();
		HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
		HttpConnectionParams.setStaleCheckingEnabled(httpParameters, false);
		HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTIONTIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParameters, SOTIMEOUT);
		HttpConnectionParams.setSocketBufferSize(httpParameters, 1024);
		HttpClientParams.setRedirecting(httpParameters, false);
		HttpClient httpclient = new DefaultHttpClient(httpParameters);
		
		HttpPost httpRequest = new HttpPost(url);
		String result = "";
		try {
			if (null != params) {
				httpRequest.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
				httpResponse = httpclient.execute(httpRequest);
				if (null != httpResponse) {
					int resCode = httpResponse.getStatusLine().getStatusCode(); // 返回码
					if (resCode == 200) {	// 网络响应成功
						result = EntityUtils.toString(httpResponse.getEntity());
					}
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();
		return result;
	}
	
	/**
	 * 已POST方式向指定url发送文本
	 * @param urlStr		指定url(不接参数)
	 * @param xmlStr		文本转换成的字符串
	 * @return				服务器的返回结果
	 */
	public static String doPost(String urlStr, String xmlStr) {
		StringBuffer sb = new StringBuffer();
		HttpResponse httpResponse = null;
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpPost httpRequest = new HttpPost(urlStr);
			StringEntity myEntity = new StringEntity(xmlStr, "UTF-8");
			httpRequest.addHeader("Content-Type", "text/xml");
			httpRequest.setEntity(myEntity);
			httpResponse = httpclient.execute(httpRequest);
			InputStream is = httpResponse.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String line = "";
			for (line = br.readLine(); null != line; line = br.readLine()) {
				sb.append(line);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();
		return sb.toString();
	}
}

2、Test.java

package http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
/**
 * 	测试类
 * @author 丑哥最风骚
 * @date 2014-02-20
 */
public class Test {

	public static void main(String[] args) {
		// 模拟GET
//		String url = "http://127.0.0.1:8080/springMVCstudy/user/testJson?userName=丑哥最风骚&password=123456";
//		String result1 = HttpUtil.doGet(url);
//		System.out.println("result1 = " + result1);
		
		// 模拟POST
//		String url = "http://127.0.0.1:8080/springMVCstudy/user/testJson?";
//		List<NameValuePair> params = new ArrayList<NameValuePair>();
//		params.add(new BasicNameValuePair("userName", "丑哥最风骚"));
//		params.add(new BasicNameValuePair("password", "123456"));
//		String result2 = HttpUtil.doPost(url, params);
//		System.out.println("result2 = " + result2);
		
		// POST XML文件
		String urlStr = "http://127.0.0.1:8080/springMVCstudy/user/testXmlPost?";
		String xmlStr = "<xml>" +
							"<userName>丑哥最风骚</userName>" +
							"<password>123456</password>" +
						"</xml>";
		String result3 = HttpUtil.doPost(urlStr, xmlStr);
		System.out.println("result3 = " + result3);
	}
}

3、服务器端针对post过来的XML的接收函数代码片段

	/**
	 * 接收客户端已HTTP方式POST过来的XML文件,并给予客户端响应
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping(value="/testXmlPost", method=RequestMethod.POST)
	public void testXmlPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		InputStream is = request.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		StringBuffer sb = new StringBuffer();
		String line = "";
		for (line = br.readLine(); line != null; line = br.readLine()) {
			sb.append(line);
		}
		String receiveStr = sb.toString();			// 接收到的XML转换成的字符串
		System.out.println("receiveStr = " + receiveStr);

		// 响应客户端
		PrintWriter out = response.getWriter();
		out.print("我已收到您发过来的XML文件");
		out.close();
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值