Android中使用HttpURLConnection实现GET POST JSON数据与下载图片

简介: Android中使用HttpURLConnection实现GET POST JSON数据与下载图片Android6.0中把Apache HTTP Client所有的包与类都标记为deprecated不再建议使用所有跟HTTP相关的数据请求与提交操作都通过HttpURLConnection类实...

Android中使用HttpURLConnection实现GET POST JSON数据与下载图片

Android6.0中把Apache HTTP Client所有的包与类都标记为deprecated不再建议使用

所有跟HTTP相关的数据请求与提交操作都通过HttpURLConnection类实现,现实是

很多Android开发者一直都Apache HTTP Client来做andoird客户端与后台HTTP接口数

据交互,本人刚刚用HttpURLConnection做了一个android的APP,不小心踩到了几个

坑,总结下最常用的就通过HttpURLConnection来POST提交JSON数据与GET请求

JSON数据。此外就是下载图片,下载图片分为显示进度与不显示进度两种。其中提交

数据的时候涉及中文一定要先把中文转码成utf-8之后在POST提交,否则就会一直遇到

HTTP 400的错误。

一:GET请求JSON数据的例子

public UserDto execute(String... params) {
	InputStream inputStream = null;
	HttpURLConnection urlConnection = null;

	try {
		// read responseURLEncoder.encode(para, "GBK");
		String urlWithParams = DOMAIN_ADDRESS + MEMBER_REQUEST_TOKEN_URL + "?userName=" + java.net.URLEncoder.encode(params[0],"utf-8") + "&password=" + params[1];
		URL url = new URL(urlWithParams);
		urlConnection = (HttpURLConnection) url.openConnection();

		/* optional request header */
		urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

		/* optional request header */
		urlConnection.setRequestProperty("Accept", "application/json");

		/* for Get request */
		urlConnection.setRequestMethod("GET");
		int statusCode = urlConnection.getResponseCode();

		/* 200 represents HTTP OK */
		if (statusCode == 200) {
			inputStream = new BufferedInputStream(urlConnection.getInputStream());
			String response = HttpUtil.convertInputStreamToString(inputStream);
			Gson gson = new Gson();
			UserDto dto = gson.fromJson(response, UserDto.class);
			if (dto != null && dto.getToken() != null) {
				Log.i("token", "find the token = " + dto.getToken());
			}
			return dto;
		}

	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (urlConnection != null) {
			urlConnection.disconnect();
		}
	}
	return null;
}
二:POST提交JSON数据

public Map<String, String> execute(NotificationDto dto) {
	InputStream inputStream = null;
	HttpURLConnection urlConnection = null;
	try {
		URL url = new URL(getUrl);
		urlConnection = (HttpURLConnection) url.openConnection();

		/* optional request header */
		urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

		/* optional request header */
		urlConnection.setRequestProperty("Accept", "application/json");
		dto.setCreator(java.net.URLEncoder.encode(dto.getCreator(), "utf-8"));
		
		// read response
		/* for Get request */
		urlConnection.setRequestMethod("POST");
		urlConnection.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
		Gson gson = new Gson();
		String jsonString = gson.toJson(dto);
		wr.writeBytes(jsonString);
		wr.flush();
		wr.close();
		// try to get response
		int statusCode = urlConnection.getResponseCode();
		if (statusCode == 200) {
			inputStream = new BufferedInputStream(urlConnection.getInputStream());
			String response = HttpUtil.convertInputStreamToString(inputStream);
			Map<String, String> resultMap = gson.fromJson(response, Map.class);
			if (resultMap != null && resultMap.size() > 0) {
				Log.i("applyDesigner", "please check the map with key");
			}
			return resultMap;
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	finally
	{
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (urlConnection != null) {
			urlConnection.disconnect();
		}
	}
	return null;
}

三:下载图片显示下载进度

package com.example.demo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ImageLoadTask extends AsyncTask<String, Void, Bitmap> {
	private Handler handler;

	public ImageLoadTask(Handler handler) {
		this.handler = handler;
	}

	protected void onPostExecute(Bitmap result) {
		Message msg = new Message();
		msg.obj = result;
		handler.sendMessage(msg);
	}

	protected Bitmap doInBackground(String... getUrls) {
		InputStream inputStream = null;
		HttpURLConnection urlConnection = null;

		try {
			// open connection
			URL url = new URL(getUrls[0]);
			urlConnection = (HttpURLConnection) url.openConnection();
			/* for Get request */
			urlConnection.setRequestMethod("GET");
			int fileLength = urlConnection.getContentLength();
			int statusCode = urlConnection.getResponseCode();
			if (statusCode == 200) {
				inputStream = urlConnection.getInputStream();
				byte data[] = new byte[4096];
				long total = 0;
				int count;
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				while ((count = inputStream.read(data)) != -1) {
					total += count;
					// publishing the progress....
					if (fileLength > 0 && handler != null) {
						handler.sendEmptyMessage(((int) (total * 100 / fileLength)) - 1);
					}
					output.write(data, 0, count);
				}
				ByteArrayInputStream bufferInput = new ByteArrayInputStream(output.toByteArray());
				Bitmap bitmap = BitmapFactory.decodeStream(bufferInput);
				inputStream.close();
				bufferInput.close();
				output.close();
				Log.i("image", "already get the image by uuid : " + getUrls[0]);
				handler.sendEmptyMessage(100);
				return bitmap;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return null;
	}

}
总结:使用HttpURLConnection提交JSON数据的时候编码方式为UTF-8

所有中文字符请一定要预先转码为UTF-8,然后在后台服务器对应的API

中解码为UTF-8,不然就会报错HTTP 400。

目录
相关文章
|
11天前
|
XML 存储 JSON
Twaver-HTML5基础学习(19)数据容器(2)_数据序列化_XML、Json
本文介绍了Twaver HTML5中的数据序列化,包括XML和JSON格式的序列化与反序列化方法。文章通过示例代码展示了如何将DataBox中的数据序列化为XML和JSON字符串,以及如何从这些字符串中反序列化数据,重建DataBox中的对象。此外,还提到了用户自定义属性的序列化注册方法。
27 1
|
8天前
|
存储 JSON Go
在Gin框架中优雅地处理HTTP请求体中的JSON数据
在Gin框架中优雅地处理HTTP请求体中的JSON数据
|
12天前
|
JSON JavaScript 数据格式
vue写入json数据到文本中+vue引入cdn的用法
vue写入json数据到文本中+vue引入cdn的用法
|
9天前
|
JSON 数据格式
Blob格式转json格式,拿到后端返回的json数据
文章介绍了如何将后端返回的Blob格式数据转换为JSON格式,并处理文件下载和错误提示。
21 0
Blob格式转json格式,拿到后端返回的json数据
|
12天前
|
JSON 前端开发 JavaScript
java中post请求调用下载文件接口浏览器未弹窗而是返回一堆json,为啥
客户端调接口需要返回另存为弹窗,下载文件,但是遇到的问题是接口调用成功且不报错,浏览器F12查看居然返回一堆json,而没有另存为弹窗; > 正确的效果应该是:接口调用成功且浏览器F12不返回任何json,而是弹窗另存为窗口,直接保存文件即可。
43 2
|
2月前
|
存储 JSON API
淘系API接口(解析返回的json数据)商品详情数据解析助力开发者
——在成长的路上,我们都是同行者。这篇关于商品详情API接口的文章,希望能帮助到您。期待与您继续分享更多API接口的知识,请记得关注Anzexi58哦! 淘宝API接口(如淘宝开放平台提供的API)允许开发者获取淘宝商品的各种信息,包括商品详情。然而,需要注意的是,直接访问淘宝的商品数据API通常需要商家身份或开发者权限,并且需要遵循淘宝的API使用协议。
淘系API接口(解析返回的json数据)商品详情数据解析助力开发者
|
25天前
|
JSON JavaScript 前端开发
Haskell中的数据交换:通过http-conduit发送JSON请求
Haskell中的数据交换:通过http-conduit发送JSON请求
|
28天前
|
存储 JSON API
Python编程:解析HTTP请求返回的JSON数据
使用Python处理HTTP请求和解析JSON数据既直接又高效。`requests`库的简洁性和强大功能使得发送请求、接收和解析响应变得异常简单。以上步骤和示例提供了一个基础的框架,可以根据你的具体需求进行调整和扩展。通过合适的异常处理,你的代码将更加健壮和可靠,为用户提供更加流畅的体验。
65 0
|
2月前
|
JSON Java API
Jackson:SpringBoot中的JSON王者,优雅掌控数据之道
【8月更文挑战第29天】在Java的广阔生态中,SpringBoot以其“约定优于配置”的理念,极大地简化了企业级应用的开发流程。而在SpringBoot处理HTTP请求与响应的过程中,JSON数据的序列化和反序列化是不可或缺的一环。在众多JSON处理库中,Jackson凭借其高效、灵活和强大的特性,成为了SpringBoot中处理JSON数据的首选。今天,就让我们一起深入探讨Jackson如何在SpringBoot中优雅地控制JSON数据。
45 0
|
2月前
|
JSON 数据处理 数据格式
Python中JSON结构数据的高效增删改操作
Python中JSON结构数据的高效增删改操作