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。

目录
相关文章
|
7月前
|
XML JavaScript Android开发
【Android】网络技术知识总结之WebView,HttpURLConnection,OKHttp,XML的pull解析方式
本文总结了Android中几种常用的网络技术,包括WebView、HttpURLConnection、OKHttp和XML的Pull解析方式。每种技术都有其独特的特点和适用场景。理解并熟练运用这些技术,可以帮助开发者构建高效、可靠的网络应用程序。通过示例代码和详细解释,本文为开发者提供了实用的参考和指导。
174 15
|
JSON API 数据格式
使用Python发送包含复杂JSON结构的POST请求
使用Python发送包含复杂JSON结构的POST请求
|
JSON 前端开发 JavaScript
java中post请求调用下载文件接口浏览器未弹窗而是返回一堆json,为啥
客户端调接口需要返回另存为弹窗,下载文件,但是遇到的问题是接口调用成功且不报错,浏览器F12查看居然返回一堆json,而没有另存为弹窗; > 正确的效果应该是:接口调用成功且浏览器F12不返回任何json,而是弹窗另存为窗口,直接保存文件即可。
447 2
|
存储 JSON 前端开发
jQuery Get 请求参数转换为 JSON
【8月更文挑战第22天】
189 2
|
JSON Java Android开发
Android 开发者必备秘籍:轻松攻克 JSON 格式数据解析难题,让你的应用更出色!
【8月更文挑战第18天】在Android开发中,解析JSON数据至关重要。JSON以其简洁和易读成为首选的数据交换格式。开发者可通过多种途径解析JSON,如使用内置的`JSONObject`和`JSONArray`类直接操作数据,或借助Google提供的Gson库将JSON自动映射为Java对象。无论哪种方法,正确解析JSON都是实现高效应用的关键,能帮助开发者处理网络请求返回的数据,并将其展示给用户,从而提升应用的功能性和用户体验。
274 1
|
JSON Android开发 数据格式
Android c++ core guideline checker 应用问题之JSON compilation database的定义如何解决
Android c++ core guideline checker 应用问题之JSON compilation database的定义如何解决
|
JSON 数据格式 Python
python3 服务端使用CGI脚本处理POST的Json数据
python3 服务端使用CGI脚本处理POST的Json数据
161 6
|
JSON PHP 数据格式
蓝易云 - PHP用CURL发送Content-type为application/json的POST请求方法
在这段代码中,我们首先创建了一个包含我们要发送的数据的数组,并使用 `json_encode`函数将其转换为JSON格式。然后,我们初始化了一个cURL会话,并设置了一些选项,包括POST请求方法、要发送的数据、返回结果和HTTP头部信息。最后,我们执行了cURL请求并关闭了会话。
482 2
|
JSON API 数据格式
如何用 Python 的 requests 库发送 JSON 数据的 POST 请求
使用 requests 库发送 JSON 数据的 POST 请求是一个非常简单且实用的操作。通过将目标 URL 和 JSON 数据传递给 requests.post 方法,你可以轻松发送请求并处理响应。本篇文章介绍了从安装 requests 库,到发送 JSON 数据的 POST 请求,再到处理响应的整个流程。希望这篇文章能帮助你更好地理解并应用这个强大的 HTTP 请求库。
|
敏捷开发 Java 机器人
云效产品使用常见问题之打包后的Android应用获取下载地址失败如何解决
云效作为一款全面覆盖研发全生命周期管理的云端效能平台,致力于帮助企业实现高效协同、敏捷研发和持续交付。本合集收集整理了用户在使用云效过程中遇到的常见问题,问题涉及项目创建与管理、需求规划与迭代、代码托管与版本控制、自动化测试、持续集成与发布等方面。

热门文章

最新文章