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

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

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

非常多Android开发人员一直都Apache HTTP Client来做andoirdclient与后台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,然后在后台server相应的API

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

Android中使用HttpURLConnection实现GET POST JSON数据与下载图片的更多相关文章

  1. HttpURLConnection从网上获取Json数据并解析详解

    HttpURLConnection从网上获取Json数据并解析 1.HttpURLConnection请求数据的步骤 (1)构造一个URL接口地址: URL url = new URL("h ...

  2. Android 学习笔记之Volley(七)实现Json数据加载和解析...

    学习内容: 1.使用Volley实现异步加载Json数据...   Volley的第二大请求就是通过发送请求异步实现Json数据信息的加载,加载Json数据有两种方式,一种是通过获取Json对象,然后 ...

  3. android中使用Intent在activity之间传递数据

    android中intent传递数据的简单使用: 1.使用intent传递数据: 首先将需要传递的数据放入到intent中 Intent intent = new Intent(MainActivit ...

  4. Android通过类对象的方式实现JSON数据的解析

    1.通过主Activity的Button按钮实现数据的解析 public class MainActivity extends Activity { //定义一个包含Json格式的字符对象 priva ...

  5. 关于iOS中几种第三方对XML/JSON数据解析的使用

    Json XML 大数据时代,我们需要从网络中获取海量的新鲜的各种信息,就不免要跟着两个家伙打交道,这是两种结构化的数据交换格式.一般来讲,我们会从网络获取XML或者Json格式的数据,这些数据有着特 ...

  6. js中对cookie的操作及json数据与cookie结合的用法

    cookie的使用 添加cookie 添加cookie:document.cookie = “key=value”; // 一次写入一个键值对 document.cookie = 'test1=hel ...

  7. Android中Textview显示Html,图文混排,支持图片点击放大

    本文首发于网易云社区 对于呈现Html文本来说,Android提供的Webview控件可以得到很好的效果,但使用Webview控件的弊端是效率相对比较低,对于呈现简单的html文本的话,杀鸡不必使用牛 ...

  8. Django中数据传输编码格式、ajax发送json数据、ajax发送文件、django序列化组件、ajax结合sweetalert做二次弹窗、批量增加数据

    前后端传输数据的编码格式(contentType) 提交post请求的两种方式: form表单 ajax请求 前后端传输数据的编码格式 urlencoded formdata(form表单里的) ja ...

  9. android中使用intent来实现Activity带数据跳转

    大家都知道startActivity()是用来切换跳转Activity的.如果想要在另个Activity中出书数据的话.只需要在源activity中使用intent.putExtra()方法传出数据. ...

随机推荐

  1. spring项目启动报错BeanFactory not initialized or already closed

    spring项目启动的时候报如下错误: java.lang.IllegalStateException: BeanFactory not initialized or already closed - ...

  2. manifest

    manifest是一种软件,属于AndroidManifest.xml文件,在简单的Android系统的应用中提出了重要的信息,它可以运行任何应用程序的代码. 每个安卓应用程序必须有一个Android ...

  3. 【06】next() 伪函数

    串行,第一个完成后,去执行第二个第二个异步任务,使用next()尾函数.首先我么想完成三个任务,task1,task2,task3,如图: 实现方式1: var fs = require(" ...

  4. iOS 初始化(init、initWithNibName、initWithCoder、initWithFrame)

    很多朋友如果是初学iOS开发,可能会被其中的几个加载方法给搞得晕头转向的,但是这几个方法又是作为iOS程序员必须要我们掌握的方法,下面我将对这几个方法做一下分析和对比,看看能不能增加大家对几个方法的理 ...

  5. T-SQL获取同类型数据不足补全的方法

    业务规则:如果有本地区的招聘会,显示本地区,如果没有本地区的招聘会,显示最近一场. 一条SQL搞定: [userId],[meetsName],[provinceId], [province],[ci ...

  6. [AGC016B] Colorful Hats (结论)

    Description 有n个人,每个人都戴着一顶帽子.当然,帽子有不同的颜色. 现在,每个人都告诉你,他看到的所有其他人的帽子共有多少种颜色,请问你有没有符合所有人的描述的情况. Input 第一行 ...

  7. [NOIP2013] 提高组 洛谷P1967 货车运输

    题目描述 A 国有 n 座城市,编号从 1 到 n,城市之间有 m 条双向道路.每一条道路对车辆都有重量限制,简称限重.现在有 q 辆货车在运输货物, 司机们想知道每辆车在不超过车辆限重的情况下,最多 ...

  8. js81:Image对象,几张图像缓存完之后动画显示,form.elements[],document.images[]

    原文发布时间为:2008-11-09 -- 来源于本人的百度文章 [由搬家工具导入] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tran ...

  9. JS读取/创建本地文件及目录文件夹的方法

    原文链接:http://www.cnblogs.com/ayan/archive/2013/04/22/3036072.html 注:以下操作只在IE下有效! Javascript是网页制作中离不开的 ...

  10. JavaScript内部是这样运行

    编译阶段 词法分析(Lexing) 这个过程会将由字符组成的字符串分解成(对编程语言来说)有意义的代码块,这些代 码块被称为词法单元(token). 简单举个例子:c = b - a 转换为 NAME ...