1、Get请求
public static Bitmap get(String urlStr) {
// 获得Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 获得HttpGet请求对象,urlStr为执行的URL,参数也是追加在URL后面
HttpGet httpGet = new HttpGet(urlStr);
Bitmap bitmap = null;
try {
// 客户端执行HttpGet对象,从而获得Http响应对象
HttpResponse httpResponse = httpClient.execute(httpGet);
// 获得响应码
int code = httpResponse.getStatusLine().getStatusCode();
if (code == 200) {
// 通过Http响应对象获得Http实体对象,再获得输入流
InputStream is = httpResponse.getEntity().getContent();
bitmap = BitmapFactory.decodeStream(is);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
// 关闭httpClient
httpClient.getConnectionManager().shutdown();
}
}
return bitmap;
}
2、Post请求
public static Bitmap post(String urlStr, Map<String, String> params) {
// 获得Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 获得HttpPost请求对象,urlStr为执行的URL
HttpPost httpPost = new HttpPost(urlStr);
Bitmap bitmap = null;
try {
/**
* 传递参数的方式,相当于HttpUrlConnection方式中的往服务器写数据的作用
*/
List<BasicNameValuePair> pair = new ArrayList<BasicNameValuePair>();
BasicNameValuePair basicNameValuePair = null;
for (Map.Entry<String, String> entry : params.entrySet()) {
// 遍历Map集合,不需要键值对的方式获取键值对
// 这里的键值对就是传递的参数
basicNameValuePair = new BasicNameValuePair(entry.getKey(),
entry.getValue());
// List集合加入BasicNameValuePair对象
pair.add(basicNameValuePair);
basicNameValuePair = null;
}
// 获得UrlEncodedFormEntity实体对象
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pair,
"UTF-8");
/**
* 如需增加请求头,可按以下键值对的方式
*/
httpPost.addHeader("Content-Length", "10");
// 设置参数的实体
httpPost.setEntity(entity);
// 客户端执行HttpPost对象,从而获得Http响应对象
HttpResponse httpResponse = httpClient.execute(httpPost);
// 获得响应码
int code = httpResponse.getStatusLine().getStatusCode();
if (code == 200) {
// 通过Http响应对象获得Http实体对象,再获得输入流
InputStream is = httpResponse.getEntity().getContent();
bitmap = BitmapFactory.decodeStream(is);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
// 关闭httpClient
httpClient.getConnectionManager().shutdown();
}
}
return bitmap;
}