下面提供一个以前写的httpclient的get 和post的传值工具,仅供个人参考
package com.shiyou.onlinevideo.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class MyHttpClient {
public static DefaultHttpClient httpClient;
public static HttpPost httpPost;
public static HttpGet httpGet;
public static HttpEntity httpEntity;
public static HttpResponse httpResponse;
/**
* get获取服务器数据
*
* @param url地址
* @return json字符串
*/
public static String executeRequestGet(String path) {
String ret = "";
try {
httpGet = new HttpGet(path);
httpClient = new DefaultHttpClient();
} catch (Exception e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
ret = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
/**
* post解析
*
* @param url地址
* @param paramsMap传入的一个map集合参数
* @return json字符串
*/
public static String executeRequestPost(String path,
Map<String, String> param) {
String ret = "";
try {
httpPost = new HttpPost(path);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : param.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httpPost.setEntity(httpEntity);
httpClient = new DefaultHttpClient();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
ret = EntityUtils.toString(entity, "utf-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
}