HttpClient发起POST请求

此函数返回请求结果

public static String executePost(String url, List<NameValuePair> params) {

		HttpPost httpPost = new HttpPost(url);
		//post请求,设置URL地址
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			//设置请求参数和编码
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
			//得到请求的结果response
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//如果状态码是200
				String result = EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);
				//得到结果, EntityUtils.toString()函数默认返回编码为ISO-8859-1,需要指定toString的第二个参数为UTF-8,否则中午乱码
				return result;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}


posted on 2014-07-23 21:49  lizhangqu  阅读(221)  评论(0编辑  收藏  举报

导航