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

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

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。

相关文章
|
2月前
|
存储 XML Java
Android 文件数据储存之内部储存 + 外部储存
简介:本文详细介绍了Android内部存储与外部存储的使用方法及核心原理。内部存储位于手机内存中,默认私有,适合存储SharedPreferences、SQLite数据库等重要数据,应用卸载后数据会被清除。外部存储包括公共文件和私有文件,支持SD卡或内部不可移除存储,需申请权限访问。文章通过代码示例展示了如何保存、读取、追加、删除文件以及将图片保存到系统相册的操作,帮助开发者理解存储机制并实现相关功能。
405 2
|
5月前
|
前端开发 Java Shell
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
303 20
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
|
8月前
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
781 4
|
9月前
|
存储 大数据 数据库
Android经典面试题之Intent传递数据大小为什么限制是1M?
在 Android 中,使用 Intent 传递数据时存在约 1MB 的大小限制,这是由于 Binder 机制的事务缓冲区限制、Intent 的设计初衷以及内存消耗和性能问题所致。推荐使用文件存储、SharedPreferences、数据库存储或 ContentProvider 等方式传递大数据。
346 0
|
10月前
|
JSON API 数据格式
使用Python发送包含复杂JSON结构的POST请求
使用Python发送包含复杂JSON结构的POST请求
|
10月前
|
JSON 前端开发 JavaScript
java中post请求调用下载文件接口浏览器未弹窗而是返回一堆json,为啥
客户端调接口需要返回另存为弹窗,下载文件,但是遇到的问题是接口调用成功且不报错,浏览器F12查看居然返回一堆json,而没有另存为弹窗; > 正确的效果应该是:接口调用成功且浏览器F12不返回任何json,而是弹窗另存为窗口,直接保存文件即可。
349 2
|
11月前
|
存储 缓存 Java
Android项目架构设计问题之优化业务接口数据的加载效率如何解决
Android项目架构设计问题之优化业务接口数据的加载效率如何解决
104 0
|
11月前
|
JSON Java Android开发
Android 开发者必备秘籍:轻松攻克 JSON 格式数据解析难题,让你的应用更出色!
【8月更文挑战第18天】在Android开发中,解析JSON数据至关重要。JSON以其简洁和易读成为首选的数据交换格式。开发者可通过多种途径解析JSON,如使用内置的`JSONObject`和`JSONArray`类直接操作数据,或借助Google提供的Gson库将JSON自动映射为Java对象。无论哪种方法,正确解析JSON都是实现高效应用的关键,能帮助开发者处理网络请求返回的数据,并将其展示给用户,从而提升应用的功能性和用户体验。
218 1
|
11月前
|
开发工具 Android开发 开发者
Android平台如何不推RTMP|不发布RTSP流|不实时录像|不回传GB28181数据时实时快照?
本文介绍了一种在Android平台上实现实时截图快照的方法,尤其适用于无需依赖系统接口的情况,如在RTMP推送、RTSP服务或GB28181设备接入等场景下进行截图。通过底层模块(libSmartPublisher.so)实现了截图功能,封装了`SnapShotImpl.java`类来管理截图流程。此外,提供了关键代码片段展示初始化SDK实例、执行截图、以及在Activity销毁时释放资源的过程。此方案还考虑到了快照数据的灵活处理需求,符合GB/T28181-2022的技术规范。对于寻求更灵活快照机制的开发者来说,这是一个值得参考的设计思路。
197 1
|
20天前
|
JSON 定位技术 PHP
PHP技巧:解析JSON及提取数据
这就是在PHP世界里探索JSON数据的艺术。这场狩猎不仅仅是为了获得数据,而是一种透彻理解数据结构的行动,让数据在你的编码海洋中畅游。通过这次冒险,你已经掌握了打开数据宝箱的钥匙。紧握它,让你在编程世界中随心所欲地航行。
120 67