HttpClient中的GET请求和POST请求

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;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值