GET请求
public static String sendRequestWithHttpClient(String url, String jason) {
String response = null;
//用HttpClient发送请求,分为五步
//第一步:创建HttpClient对象
HttpClient httpCient = new DefaultHttpClient();
//第二步:创建代表请求的对象,参数是访问的服务器地址
HttpPost httpPost = new HttpPost(url + jason);
try {
//第三步:执行请求,获取服务器发还的相应对象
HttpResponse httpResponse = httpCient.execute(httpPost);
//第四步:检查相应的状态是否正常:检查状态码的值是200表示正常
if (httpResponse.getStatusLine().getStatusCode() == 200) {
//第五步:从相应对象当中取出数据,放到entity当中
HttpEntity entity = httpResponse.getEntity();
//将entity当中的数据转换为字符串
response = EntityUtils.toString(entity, "utf-8");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
POST请求:
public static String postStringEntity(String url, JSONObject body) throws IOException {
HttpClient httpClient = HttpUtil.genHttpClient();
HttpPost post = new HttpPost(url);
//这里json千万不要encode,否则会解析不出来
StringEntity entity = new StringEntity(body.toString(), "UTF-8");
HttpContext context = new BasicHttpContext();
post.setEntity(entity);
HttpResponse response = httpClient.execute(post, context);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
return result;
}
jar包下载:
http://note.youdao.com/noteshare?id=125a5f56afa958b29035c3611dce04fa