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。

相关文章
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
1420 4
|
8月前
|
安全 数据库 Android开发
在Android开发中实现两个Intent跳转及数据交换的方法
总结上述内容,在Android开发中,Intent不仅是活动跳转的桥梁,也是两个活动之间进行数据交换的媒介。运用Intent传递数据时需注意数据类型、传输大小限制以及安全性问题的处理,以确保应用的健壯性和安全性。
556 11
|
10月前
|
存储 XML Java
Android 文件数据储存之内部储存 + 外部储存
简介:本文详细介绍了Android内部存储与外部存储的使用方法及核心原理。内部存储位于手机内存中,默认私有,适合存储SharedPreferences、SQLite数据库等重要数据,应用卸载后数据会被清除。外部存储包括公共文件和私有文件,支持SD卡或内部不可移除存储,需申请权限访问。文章通过代码示例展示了如何保存、读取、追加、删除文件以及将图片保存到系统相册的操作,帮助开发者理解存储机制并实现相关功能。
2524 2
|
前端开发 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
855 20
【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
|
XML JavaScript Android开发
【Android】网络技术知识总结之WebView,HttpURLConnection,OKHttp,XML的pull解析方式
本文总结了Android中几种常用的网络技术,包括WebView、HttpURLConnection、OKHttp和XML的Pull解析方式。每种技术都有其独特的特点和适用场景。理解并熟练运用这些技术,可以帮助开发者构建高效、可靠的网络应用程序。通过示例代码和详细解释,本文为开发者提供了实用的参考和指导。
472 15
|
6月前
|
机器学习/深度学习 JSON 监控
淘宝拍立淘按图搜索与商品详情API的JSON数据返回详解
通过调用taobao.item.get接口,获取商品标题、价格、销量、SKU、图片、属性、促销信息等全量数据。
|
5月前
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:
|
5月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
5月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
6月前
|
JSON 缓存 自然语言处理
多语言实时数据微店商品详情API:技术实现与JSON数据解析指南
通过以上技术实现与解析指南,开发者可高效构建支持多语言的实时商品详情系统,满足全球化电商场景需求。

热门文章

最新文章