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。

相关文章
|
4月前
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:
|
4月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
4月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
5月前
|
JSON 缓存 自然语言处理
多语言实时数据微店商品详情API:技术实现与JSON数据解析指南
通过以上技术实现与解析指南,开发者可高效构建支持多语言的实时商品详情系统,满足全球化电商场景需求。
|
4月前
|
JSON 中间件 Java
【GoGin】(3)Gin的数据渲染和中间件的使用:数据渲染、返回JSON、浅.JSON()源码、中间件、Next()方法
我们在正常注册中间件时,会打断原有的运行流程,但是你可以在中间件函数内部添加Next()方法,这样可以让原有的运行流程继续执行,当原有的运行流程结束后再回来执行中间件内部的内容。​ c.Writer.WriteHeaderNow()还会写入文本流中。可以看到使用next后,正常执行流程中并没有获得到中间件设置的值。接口还提供了一个可以修改ContentType的方法。判断了传入的状态码是否符合正确的状态码,并返回。在内部封装时,只是标注了不同的render类型。再看一下其他返回的类型;
253 4
|
4月前
|
JSON Java Go
【GoGin】(2)数据解析和绑定:结构体分析,包括JSON解析、form解析、URL解析,区分绑定的Bind方法
bind或bindXXX函数(后文中我们统一都叫bind函数)的作用就是将,以方便后续业务逻辑的处理。
338 3
|
5月前
|
JSON API 数据安全/隐私保护
Python采集淘宝评论API接口及JSON数据返回全流程指南
Python采集淘宝评论API接口及JSON数据返回全流程指南
|
5月前
|
JSON 自然语言处理 监控
淘宝关键词搜索与商品详情API接口(JSON数据返回)
通过商品ID(num_iid)获取商品全量信息,包括SKU规格、库存、促销活动、卖家信息、详情页HTML等。
|
5月前
|
JSON 自然语言处理 API
多语言实时数据淘宝商品评论API:技术实现与JSON数据解析指南
淘宝商品评论多语言实时采集需结合官方API与后处理技术实现。建议优先通过地域站点适配获取本地化评论,辅以机器翻译完成多语言转换。在合规前提下,企业可构建多语言评论数据库,支撑全球化市场分析与产品优化。
|
5月前
|
机器学习/深度学习 JSON API
干货,淘宝拍立淘按图搜索,淘宝API(json数据返回)
淘宝拍立淘按图搜索API接口基于深度学习与计算机视觉技术,通过解析用户上传的商品图片,在淘宝商品库中实现毫秒级相似商品匹配,并以JSON格式返回商品标题、图片链接、价格、销量、相似度评分等详细信息。

热门文章

最新文章