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。

以上就是本文的全部内容,希望对大家的学习Android软件编程有所帮助。

时间: 2024-07-28 13:40:03

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

android中如何解析没有Key的Json数据

新浪微博有一部分json数据如下,你会发现这是个数组,但是数组没有key,数组中的对象也没有key.怎么解析呢?fastjson遇到这种无名数组套无名对象也会报异常.所以建议使用原生的json解析. 一.问题: 二.解析代码: com.ht.weibo.weibomodel; com.sina.weibo.sdk.openapi.models.Status; org.json.JSONArray; org.json.JSONException; org.json.JSONObject; java

Android中的JSONObject和JSONArray解析json数据

       String strJson = "{"students":[{"name":"Jack","age":12}, {"name":"Vista","age":23}, {"name":"Kaka","age":22}, {"name":"Hony"

编码-jQuery中的ajax方法获取到json数据中文会乱码

问题描述 jQuery中的ajax方法获取到json数据中文会乱码 接口如下:http://cre.mix.sina.com.cn/api/finance/topstock_display这个接口 默认返回是 gbk的编码 支持 oe=utf-8,但是xtmlhttprequest 返回的数据默认的字符编码是utf-8,后台说用oe=utf转换,求解... 解决方案 首先你这不是json,所以你需要从服务器语言上把数据转换成json再去传到前端:其次,你要把后台脚本改成utf-8编码,不知道你用

android中多台手机通过wifi进行数据传递

问题描述 android中多台手机通过wifi进行数据传递 是这样的,一台手机作为服务器,其他手机作为客户端,通过wifi怎么实现数据传递, 客户端可以主动发消息给服务端,服务端也可以主动发消息给客户端. 哪位大大知道怎么实现... 目前已经实现了一个服务器与一个客户端的连接.但是服务端没法主动给客户端发消息 新手..没什么币... 解决方案 jdk还是ndk? 服务端一般是循环监听消息,而客户端是发出消息,每台手机都是融合服务端和客户端的,获得自己的局域网IP,然后获取特征,在这个地址段前后的

隐藏-Android中的webview加载完成前后如何用一个图片来进行遮挡加载延迟的闪烁

问题描述 Android中的webview加载完成前后如何用一个图片来进行遮挡加载延迟的闪烁 用webview加载一个链接,但因为网速或者网页内容等问题,出现延迟,但是如果直接打开APP就开始加载的话,如果用户没有网络的情况下打开APP就什么都看不到了.所以想整个LOGO之类的全屏图片,等加载完成了之后再隐藏这个图片.该怎么实现,着急,在线等..... 解决方案 做个全屏的layout,等webview加载完就隐藏掉,在onPageFinished里处理 加载前可以先判断网络是不连通,不通就显示

在Action中以Struts2的方式输出JSON数据的实例_java

下面是整个Action的完整代码: package cn.ysh.studio.struts2.json.demo.action; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.Servlet

JS中如何判断传过来的JSON数据中是否存在某字段_javascript技巧

如何判断传过来的JSON数据中,某个字段是否存在, 1.obj["key"] != undefined 这种有缺陷,如果这个key定义了,并且就是很2的赋值为undefined,那么这句就会出问题了. 2.!("key" in obj) 3.obj.hasOwnProperty("key") 这两种方法就比较好了,推荐使用. 答案原文: Actually, checking for undefined-ness is not an accurat

Android中如何制作电池电量进度条:上下滚动图片的进度条(battery)

最近,制作一个app,需要模拟一个电池电量的进度条,根据电量多少来设置百分比,进度条不断上下滚动,就像平时手机充电一样的电池电量进度条.我就自定义view实现了电量进度条.修改图片就可以达到自己想要的效果 一.自定义View,Battery.java,循环刷新界面,两张图片上下滚动,达到不断向右移动的效果.挺有意思的 package com.example.battery; import android.content.Context; import android.content.res.Re

Android中Retrofit 2.0直接使用JSON进行数据交互

之前使用Retrofit都是将JSON串转化为POJO对象,针对不同的业务协议,定义相应的接口和参数列表.但是此种方式一般用在自己内部协议基础上,具体大的项目中,有些第三方的集成功能,一般都采用统一的方式即请求JSON和回应JSON进行数据交互,不可能每个第三方协议都会去定义与协议相应的POJO对象. HTTP肯定有GET和POST方法,先定义Retrofit Api的interface: package com.hdnetworklib.network.http; import java.ut