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

 更新时间:2016年01月14日 11:16:25   作者:gloomyfish  
这篇文章主要介绍了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软件编程有所帮助。

相关文章

  • Android崩溃日志收集和保存解析

    Android崩溃日志收集和保存解析

    这篇文章主要为大家介绍了Android崩溃日志收集和保存解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Android 图片存储到指定路径和相册的方法

    Android 图片存储到指定路径和相册的方法

    本篇文章主要介绍了Android 图片存储到指定路径和相册的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07
  • Android Fragment滑动组件ViewPager的实例详解

    Android Fragment滑动组件ViewPager的实例详解

    这篇文章主要介绍了Android Fragment滑动组件ViewPager的实例详解的相关资料,需要的朋友可以参考下
    2017-05-05
  • 在Android中调用WebService实例

    在Android中调用WebService实例

    这篇文章主要介绍了在Android中调用WebService实例,有需要的朋友可以了解一下。
    2016-11-11
  • kotlin中使用ViewBinding绑定控件的方法

    kotlin中使用ViewBinding绑定控件的方法

    View Binding是Android Studio 3.6推出的新特性,主要用于减少findViewById的冗余代码,但内部实现还是通过使用findViewById,这篇文章主要介绍了kotlin中使用ViewBinding绑定控件,需要的朋友可以参考下
    2024-03-03
  • Android WebView无法弹出软键盘的原因及解决办法

    Android WebView无法弹出软键盘的原因及解决办法

    这篇文章主要介绍了Android WebView无法弹出软键盘的原因及解决办法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • Android中通过MediaStore获取音乐文件信息方法

    Android中通过MediaStore获取音乐文件信息方法

    这篇文章主要介绍了Android中通过MediaStore获取音乐文件信息方法,本文讲解了获取歌曲的名称、歌曲的专辑名、歌曲的歌手名、歌曲文件的全路径、歌曲文件的名称、歌曲文件的发行日期等音乐文件信息的方法,需要的朋友可以参考下
    2015-04-04
  • Android Socket通信实现简单聊天室

    Android Socket通信实现简单聊天室

    这篇文章主要为大家详细介绍了Android网络编程之Socket通信实现简单聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • Android应用中加入微信分享简单方法

    Android应用中加入微信分享简单方法

    这篇文章主要介绍了Android应用中加入微信分享简单方法,本文用简洁明快的步骤讲解了加入微信分享的方法,需要的朋友可以参考下
    2015-05-05
  • Android 8.0系统中应用图标的适配技巧

    Android 8.0系统中应用图标的适配技巧

    今天小编就为大家分享一篇关于Android 8.0系统中应用图标的适配技巧,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10

最新评论