apache Http post方式

public String doPost(String url, Map<String, String> params) {
		String response = null;
		log.info("url为:" + url + ",params为:" + params);

		HttpClient httpClient = new HttpClient();// 创建一个客户端,类似打开一个浏览器
		httpClient.getParams().setContentCharset("utf-8");// 设置编码格式
		
		PostMethod postMethod = new PostMethod(url);// 创建一个post方法,类似在浏览器地址栏中输入一个地址

		NameValuePair[] postData = new NameValuePair[params.size()];// POST需要通过NameValuePair类来设置参数名称和它所对应的值
		// 设置Http Post数据
		if (params != null) {
			int count = 0;
			for (Map.Entry<String, String> entry : params.entrySet()) {
				postData[count] = new NameValuePair(entry.getKey(), entry.getValue());
				count++;
			}
			postMethod.addParameters(postData);
		}
		try {
			log.info("执行post方法开始");
			httpClient.executeMethod(postMethod);// 执行,类似于回车键
			log.info("执行post方法结束");
			log.info("method.getStatusCode()=" + postMethod.getStatusCode());
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				log.info("获取返回值开始");
				response = postMethod.getResponseBodyAsString();
				log.info("获取返回值结束,response为:" + response);
			}
		} catch (Exception e) {
			log.error("post发生异常:" + e);
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();// 释放
			log.info("释放链接");
		}
		return response;
	}
对于编码方式可以有以下几种方式,应该都可以的,我只用了其中一种:
httpClient.getParams().setContentCharset("utf-8");// TODO
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");// TODO
 
postMethod.getParams().setContentCharset("utf-8");// TODO
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");// TODO
postMethod.setQueryString(EncodingUtil.formUrlEncode(postData, "utf-8"));// TODO

你可能感兴趣的:(response,编码,utf-8,dopost)