Android之网络访问

1,httpClient

	// 获取二维码
	// 返回bitmap或null
	public static Bitmap get2DCodePic(String box_id) {

		// todo
		// Toast.makeText(getApplicationContext(), "todo\n", Toast.LENGTH_LONG)
		// .show();

		String result = null;
		BufferedReader reader = null;

		try {

			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(Tools.GET_2DCODE_PIC + box_id));
			HttpResponse response = client.execute(request);
			reader = new BufferedReader(new InputStreamReader(response
					.getEntity().getContent()));
			StringBuffer strBuffer = new StringBuffer("");
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
			result = strBuffer.toString();

			// Toast.makeText(getApplicationContext(), result,
			// Toast.LENGTH_LONG)
			// .show();

			Bitmap bitmap = Tools.getHttpBitmap(result);
			if (null != bitmap) {
				Matrix matrix = new Matrix();
				matrix.postScale(0.7f, 0.7f); // 长和宽放大缩小的比例
				Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0,
						bitmap.getWidth(), bitmap.getHeight(), matrix, true);
				return resizeBmp;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


2,httpURLConnection

	/*
	 * function: input:图片url output:图片bitmap
	 */
	public static Bitmap getHttpBitmap(String url) {
		Log.d(Tools.LOG_TAG, url);
		URL myFileURL;
		Bitmap bitmap = null;
		try {
			myFileURL = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myFileURL
					.openConnection();
			// 设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
			conn.setConnectTimeout(6000);
			// 连接设置获得数据流
			conn.setDoInput(true);
			// 不使用缓存
			conn.setUseCaches(false);
			// 这句可有可无,没有影响
			// conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}


3,第三方库(imageloader,volley)

待续。。。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值