需要导入的包
package httpclient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
/**
*
* @param url 地址
* @param jsonParam 传输入参数
* @param contentType http Content-Type 类型 例如 Content-Type: text/html;charset:utf-8;
* @return
* @throws Exception
*/
public String postMethod(String url, String jsonParam,String contentType) throws Exception {
//创建一个客户端
DefaultHttpClient httpClient = new DefaultHttpClient();
//创建HttpPost对象,将要请求的URL通过构造方法传入HttpPost对象。
HttpPost method = new HttpPost(url);
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType(contentType);
method.setEntity(entity);
}
//用execute方法发送HTTP post请求,并返回HttpResponse对象。
HttpResponse result = httpClient.execute(method);
//判断请求是否发送成功
String str = "";
if (result.getStatusLine().getStatusCode() == 200) {
//读取返回的数据
str = EntityUtils.toString(result.getEntity());
} else {
System.out.println("失败");
}
return str;
}
/**
*
* @param url 地址
* @param jsonParam 传输入参数
* @param contentType http Content-Type 类型 例如 Content-Type: text/html;charset:utf-8;
* @return
* @throws Exception
*/
public String getMethod(String url) throws Exception {
//创建一个客户端
DefaultHttpClient httpClient = new DefaultHttpClient();
//创建HttpPost对象,将要请求的URL通过构造方法传入HttpPost对象。
HttpGet method = new HttpGet(url);
//用execute方法发送HTTP post请求,并返回HttpResponse对象。
HttpResponse result = httpClient.execute(method);
String str = "";
//判断请求是否发送成功
if (result.getStatusLine().getStatusCode() == 200) {
//读取返回的数据
str = EntityUtils.toString(result.getEntity());
} else {
System.out.println("失败");
}
return str;
}
}