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数据的样例

  1. public UserDto execute(String... params) {
  2. InputStream inputStream = null;
  3. HttpURLConnection urlConnection = null;
  4.  
  5. try {
  6. // read responseURLEncoder.encode(para, "GBK");
  7. String urlWithParams = DOMAIN_ADDRESS + MEMBER_REQUEST_TOKEN_URL + "?userName=" + java.net.URLEncoder.encode(params[0],"utf-8") + "&password=" + params[1];
  8. URL url = new URL(urlWithParams);
  9. urlConnection = (HttpURLConnection) url.openConnection();
  10.  
  11. /* optional request header */
  12. urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  13.  
  14. /* optional request header */
  15. urlConnection.setRequestProperty("Accept", "application/json");
  16.  
  17. /* for Get request */
  18. urlConnection.setRequestMethod("GET");
  19. int statusCode = urlConnection.getResponseCode();
  20.  
  21. /* 200 represents HTTP OK */
  22. if (statusCode == 200) {
  23. inputStream = new BufferedInputStream(urlConnection.getInputStream());
  24. String response = HttpUtil.convertInputStreamToString(inputStream);
  25. Gson gson = new Gson();
  26. UserDto dto = gson.fromJson(response, UserDto.class);
  27. if (dto != null && dto.getToken() != null) {
  28. Log.i("token", "find the token = " + dto.getToken());
  29. }
  30. return dto;
  31. }
  32.  
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. } finally {
  36. if (inputStream != null) {
  37. try {
  38. inputStream.close();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. if (urlConnection != null) {
  44. urlConnection.disconnect();
  45. }
  46. }
  47. return null;
  48. }

二:POST提交JSON数据

  1. public Map<String, String> execute(NotificationDto dto) {
  2. InputStream inputStream = null;
  3. HttpURLConnection urlConnection = null;
  4. try {
  5. URL url = new URL(getUrl);
  6. urlConnection = (HttpURLConnection) url.openConnection();
  7.  
  8. /* optional request header */
  9. urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  10.  
  11. /* optional request header */
  12. urlConnection.setRequestProperty("Accept", "application/json");
  13. dto.setCreator(java.net.URLEncoder.encode(dto.getCreator(), "utf-8"));
  14.  
  15. // read response
  16. /* for Get request */
  17. urlConnection.setRequestMethod("POST");
  18. urlConnection.setDoOutput(true);
  19. DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
  20. Gson gson = new Gson();
  21. String jsonString = gson.toJson(dto);
  22. wr.writeBytes(jsonString);
  23. wr.flush();
  24. wr.close();
  25. // try to get response
  26. int statusCode = urlConnection.getResponseCode();
  27. if (statusCode == 200) {
  28. inputStream = new BufferedInputStream(urlConnection.getInputStream());
  29. String response = HttpUtil.convertInputStreamToString(inputStream);
  30. Map<String, String> resultMap = gson.fromJson(response, Map.class);
  31. if (resultMap != null && resultMap.size() > 0) {
  32. Log.i("applyDesigner", "please check the map with key");
  33. }
  34. return resultMap;
  35. }
  36. }
  37. catch(Exception e)
  38. {
  39. e.printStackTrace();
  40. }
  41. finally
  42. {
  43. if (inputStream != null) {
  44. try {
  45. inputStream.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. if (urlConnection != null) {
  51. urlConnection.disconnect();
  52. }
  53. }
  54. return null;
  55. }

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

  1. package com.example.demo;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9.  
  10. import android.graphics.Bitmap;
  11. import android.graphics.BitmapFactory;
  12. import android.os.AsyncTask;
  13. import android.os.Handler;
  14. import android.os.Message;
  15. import android.util.Log;
  16.  
  17. public class ImageLoadTask extends AsyncTask<String, Void, Bitmap> {
  18. private Handler handler;
  19.  
  20. public ImageLoadTask(Handler handler) {
  21. this.handler = handler;
  22. }
  23.  
  24. protected void onPostExecute(Bitmap result) {
  25. Message msg = new Message();
  26. msg.obj = result;
  27. handler.sendMessage(msg);
  28. }
  29.  
  30. protected Bitmap doInBackground(String... getUrls) {
  31. InputStream inputStream = null;
  32. HttpURLConnection urlConnection = null;
  33.  
  34. try {
  35. // open connection
  36. URL url = new URL(getUrls[0]);
  37. urlConnection = (HttpURLConnection) url.openConnection();
  38. /* for Get request */
  39. urlConnection.setRequestMethod("GET");
  40. int fileLength = urlConnection.getContentLength();
  41. int statusCode = urlConnection.getResponseCode();
  42. if (statusCode == 200) {
  43. inputStream = urlConnection.getInputStream();
  44. byte data[] = new byte[4096];
  45. long total = 0;
  46. int count;
  47. ByteArrayOutputStream output = new ByteArrayOutputStream();
  48. while ((count = inputStream.read(data)) != -1) {
  49. total += count;
  50. // publishing the progress....
  51. if (fileLength > 0 && handler != null) {
  52. handler.sendEmptyMessage(((int) (total * 100 / fileLength)) - 1);
  53. }
  54. output.write(data, 0, count);
  55. }
  56. ByteArrayInputStream bufferInput = new ByteArrayInputStream(output.toByteArray());
  57. Bitmap bitmap = BitmapFactory.decodeStream(bufferInput);
  58. inputStream.close();
  59. bufferInput.close();
  60. output.close();
  61. Log.i("image", "already get the image by uuid : " + getUrls[0]);
  62. handler.sendEmptyMessage(100);
  63. return bitmap;
  64. }
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. } finally {
  68. if (inputStream != null) {
  69. try {
  70. inputStream.close();
  71. } catch (IOException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. if (urlConnection != null) {
  76. urlConnection.disconnect();
  77. }
  78. }
  79. return null;
  80. }
  81.  
  82. }

总结:使用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. nodeJS(2)深了解: nodeJS 项目架构详解(app.js + Express + Http)

    简略了解:nodeJS 深了解(1): Node.js + Express 构建网站预备知识 环境: 环境: win7 + nodeJS 版本(node): 新建 nodeJS 项目: 名称为: te ...

  2. linux之软硬链接【转】

    链接---------是一种在共享文件和访问它的用户的若干目录项之间建立联系的一种方法. Linux中包括两种链接:硬链接(Hard Link)和软链接(Soft Link),软链接又称为符号链接(S ...

  3. 【CodeChef】PARADE(费用流,最短路)

    题意: 思路: #include<cstdio> #include<iostream> #include<algorithm> #include<cstrin ...

  4. 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---56

    以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下:

  5. Swift Perfect 基础项目

    brew install mysql@5.7 && brew link mysql@5.7 --force Package.swift import PackageDescriptio ...

  6. springBoot 环境

    环境约束 jdk1.8:Spring Boot 推荐jdk1.7及以上:maven3.x:maven 3.3以上版本:Apache Maven 3.3.9.IntelliJIDEA2017:Intel ...

  7. AC日记——[NOI2006]最大获利 bzoj 1497

    1497 思路: 最小割: 来,上代码: #include <cstdio> #include <cstring> #include <iostream> #inc ...

  8. openshift scc解析

    SCC使用UserID,FsGroupID以及supplemental group ID和SELinux label等策略,通过校验Pod定义的ID是否在有效范围内来限制pod的权限.如果校验失败,则 ...

  9. 10.1综合强化刷题 Day2 morning

    一道图论神题(god) Time Limit:1000ms   Memory Limit:128MB 题目描述 LYK有一张无向图G={V,E},这张无向图有n个点m条边组成.并且这是一张带权图,只有 ...

  10. http重定向https

    server { listen 80; server_name localhost; return 301 https://$host$request_uri; } server { listen 4 ...