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

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

概述Android6.0中把ApacheHTTPClient所有的包与类都标记为deprecated不再建议使用所有跟HTTP相关的数据请求与提交 *** 作都通过HttpURLConnection类实现,现实是很多Android开发者一直都ApacheHTTPClient来做andoird客户端与

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");   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,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中使用HttpURLConnection实现GET POST JSON数据与下载图片全部内容,希望文章能够帮你解决Android中使用HttpURLConnection实现GET POST JSON数据与下载图片所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1141807.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存