下面是最早从事android开发的时候写的网络请求的代码,简单高效,对于理解http请求有帮助。直接上代码,不用解释,因为非常简单。

  1. import java.io.BufferedReader;
  2. import java.io.DataOutputStream;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLEncoder;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. import org.apache.http.entity.mime.content.FileBody;
  13.  
  14. import android.util.Log;
  15.  
  16. public class HttpRequest {
  17.  
  18. public static final String UTF_8 = "UTF-8";
  19.  
  20. private static String cookie = null;
  21.  
  22. /**
  23. * GET请求
  24. *
  25. * @param actionUrl
  26. * @param params
  27. * @return
  28. */
  29. public static String httpGet(String actionUrl, Map<String, String> params) {
  30. try{
  31. StringBuffer urlbuff = new StringBuffer(actionUrl);
  32. if (params != null && params.size() > 0) {
  33. if (actionUrl.indexOf("?") >= 0) {
  34. urlbuff.append("&");
  35. } else {
  36. urlbuff.append("?");
  37. }
  38. for (String key : params.keySet()) {
  39. urlbuff.append(key).append("=").append(URLEncoder.encode(params.get(key), UTF_8)).append("&");
  40. }
  41. urlbuff.deleteCharAt(urlbuff.length() - 1);
  42. Log.v("---request---Get---", urlbuff.toString());
  43. }
  44. URL url = new URL(urlbuff.toString());
  45. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  46. conn.setDoInput(true);// 允许输入
  47. conn.setDoOutput(false);// 允许输出
  48. conn.setUseCaches(false);// 不使用Cache
  49. conn.setRequestMethod("GET");
  50. conn.setRequestProperty("Charset", UTF_8);
  51. if (cookie != null) {
  52. conn.setRequestProperty("Cookie", cookie);
  53. }
  54. int cah = conn.getResponseCode();
  55. if (cah != 200)
  56. throw new RuntimeException("请求url失败");
  57. if (conn.getHeaderField("Set-Cookie") != null) {
  58. cookie = conn.getHeaderField("Set-Cookie");
  59. }
  60. Log.i("", "------------------cookie:" + cookie);
  61. Map<String, List<String>> keys = conn.getHeaderFields();
  62. for(String key : keys.keySet()) {
  63. List<String> list = keys.get(key);
  64. for(String value : list) {
  65. Log.i("", "header: key:" + key + " values:" + value);
  66. }
  67. }
  68.  
  69. InputStream is = conn.getInputStream();
  70. int ch;
  71. StringBuilder b = new StringBuilder();
  72. while ((ch = is.read()) != -1) {
  73. b.append((char) ch);
  74. }
  75. is.close();
  76. conn.disconnect();
  77. return b.toString();
  78. }catch(Exception e) {
  79. e.printStackTrace();
  80. }
  81. return null;
  82. }
  83.  
  84. /**
  85. * post 带文件上传
  86. * @param actionUrl
  87. * @param params
  88. * @param files
  89. * @return
  90. */
  91. public static String httpPost(String actionUrl, Map<String, String> params, Map<String, FileBody> files) {
  92. String LINE_START = "--";
  93. String LINE_END = "\r\n";
  94. String BOUNDRY = "*****";
  95.  
  96. try{
  97. HttpURLConnection conn = null;
  98. DataOutputStream dos = null;
  99.  
  100. int bytesRead, bytesAvailable, bufferSize;
  101. long totalBytes;
  102. byte[] buffer;
  103. int maxBufferSize = 8096;
  104.  
  105. URL url = new URL(actionUrl);
  106. conn = (HttpURLConnection) url.openConnection();
  107.  
  108. // Allow Inputs
  109. conn.setDoInput(true);
  110.  
  111. // Allow Outputs
  112. conn.setDoOutput(true);
  113.  
  114. // Don't use a cached copy.
  115. conn.setUseCaches(false);
  116.  
  117. // Use a post method.
  118. conn.setRequestMethod("POST");
  119. //if (files != null && files.size() > 0) {
  120. conn.setRequestProperty("Connection", "Keep-Alive");
  121. conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
  122. //}
  123.  
  124. Log.i("", "cookie:" + cookie);
  125. if (cookie != null) {
  126. conn.setRequestProperty("Cookie", cookie);
  127. }
  128. // // Set the cookies on the response
  129. // String cookie = CookieManager.getInstance().getCookie(server);
  130. // if (cookie != null) {
  131. // conn.setRequestProperty("Cookie", cookie);
  132. // }
  133.  
  134. // // Should set this up as an option
  135. // if (chunkedMode) {
  136. // conn.setChunkedStreamingMode(maxBufferSize);
  137. // }
  138.  
  139. dos = new DataOutputStream(conn.getOutputStream());
  140.  
  141. // Send any extra parameters
  142. for (Object key : params.keySet()) {
  143. dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
  144. dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"" + LINE_END);
  145. dos.writeBytes(LINE_END);
  146. dos.write(params.get(key).getBytes());
  147. dos.writeBytes(LINE_END);
  148.  
  149. Log.i("", "-----key:" + key + " value:" + params.get(key));
  150. }
  151. //-----------
  152. if (files != null && files.size() > 0) {
  153. for (String key : files.keySet()) {
  154. Log.i("", "-----key:" + key + " value:" + params.get(key));
  155. FileBody fileBody = files.get(key);
  156. dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
  157. dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\";" + " filename=\"" + fileBody.getFilename() +"\"" + LINE_END);
  158. dos.writeBytes("Content-Type: " + fileBody.getMimeType() + LINE_END);
  159. dos.writeBytes(LINE_END);
  160.  
  161. // Get a input stream of the file on the phone
  162. InputStream fileInputStream = new FileInputStream(fileBody.getFile());
  163. bytesAvailable = fileInputStream.available();
  164. bufferSize = Math.min(bytesAvailable, maxBufferSize);
  165. buffer = new byte[bufferSize];
  166. // read file and write it into form...
  167. bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  168. totalBytes = 0;
  169. while (bytesRead > 0) {
  170. totalBytes += bytesRead;
  171. //result.setBytesSent(totalBytes);
  172. dos.write(buffer, 0, bufferSize);
  173. bytesAvailable = fileInputStream.available();
  174. bufferSize = Math.min(bytesAvailable, maxBufferSize);
  175. bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  176. }
  177. dos.writeBytes(LINE_END);
  178. // close streams
  179. fileInputStream.close();
  180. }
  181. }
  182. dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);
  183. dos.flush();
  184. dos.close();
  185.  
  186. int statusCode = conn.getResponseCode();
  187. Log.i("", "---------------statusCode:" + statusCode);
  188. if (statusCode != 200) {
  189. throw new HttpRequestException("server error");
  190. }
  191.  
  192. //------------------ read the SERVER RESPONSE
  193. InputStream is = conn.getInputStream();
  194. int ch;
  195. StringBuilder b = new StringBuilder();
  196. while ((ch = is.read()) != -1) {
  197. b.append((char) ch);
  198. }
  199. conn.disconnect();
  200.  
  201. return b.toString();
  202. }catch(Exception e){
  203. Log.i("", "---------------" + e.getMessage(), e.fillInStackTrace());
  204. e.printStackTrace();
  205. }
  206. return null;
  207. }
  208.  
  209. /**
  210. * post请求
  211. * @param actionUrl
  212. * @param params
  213. * @return
  214. */
  215. public static String httpPost(String actionUrl, Map<String, String> params){
  216. try{
  217. URL url = new URL(actionUrl);
  218. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  219. //因为这个是post请求,设立需要设置为true
  220. conn.setDoOutput(true);
  221. conn.setDoInput(true);
  222. // 设置以POST方式
  223. conn.setRequestMethod("POST");
  224. // Post 请求不能使用缓存
  225. conn.setUseCaches(false);
  226. conn.setInstanceFollowRedirects(true);
  227. // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
  228. conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  229. // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
  230. // 要注意的是connection.getOutputStream会隐含的进行connect。
  231. if (cookie != null) {
  232. conn.setRequestProperty("Cookie", cookie);
  233. }
  234. conn.connect();
  235. //DataOutputStream流
  236. DataOutputStream out = new DataOutputStream(conn.getOutputStream());
  237. //要上传的参数
  238. StringBuffer content = new StringBuffer();
  239. for (String key : params.keySet()) {
  240. //String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
  241. content.append(key).append("=").append(params.get(key)).append("&");
  242. }
  243. //将要上传的内容写入流中
  244. out.writeBytes(content.toString());
  245. //刷新、关闭
  246. out.flush();
  247. out.close();
  248.  
  249. int statusCode = conn.getResponseCode();
  250. Log.i("", "---------------statusCode:" + statusCode);
  251. if (statusCode != 200) {
  252. throw new HttpRequestException("server error");
  253. }
  254. if (conn.getHeaderField("Set-Cookie") != null) {
  255. cookie = conn.getHeaderField("Set-Cookie");
  256. }
  257. //获取数据
  258. InputStream is = conn.getInputStream();
  259. int ch;
  260. StringBuilder b = new StringBuilder();
  261. while ((ch = is.read()) != -1) {
  262. b.append((char) ch);
  263. }
  264. conn.disconnect();
  265. return b.toString();
  266. }catch(Exception e) {
  267. Log.i("", "---------------" + e.getMessage(), e.fillInStackTrace());
  268. e.printStackTrace();
  269. }
  270. return null;
  271. }
  272.  
  273. }

1. application/x-www-form-urlencoded

最常见的 POST 提交数据的方式了。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded方式提交数据。 
传递的key/val会经过URL转码,所以如果传递的参数存在中文或者特殊字符需要注意。

  1. //例子
  2. //b=曹,a=1
  3.  
  4. POST HTTP/1.1(CRLF)
  5. Host: www.example.com(CRLF)
  6. Content-Type: application/x-www-form-urlencoded(CRLF)
  7. Cache-Control: no-cache(CRLF)
  8. (CRLF)
  9. b=%E6%9B%B9&a=1(CRLF)
  10. //这里b参数的值"曹"因为URL转码变成其他的字符串了

2. text/xml

  1. //例子
  2.  
  3. POST http://www.example.com HTTP/1.1(CRLF)
  4. Content-Type: text/xml(CRLF)
  5. (CRLF)
  6. <?xml version="1.0"?>
  7. <resource>
  8. <id>123</id>
  9. <params>
  10. <name>
  11. <value>homeway</value>
  12. </name>
  13. <age>
  14. <value>22</value>
  15. </age>
  16. </params>
  17. </resource>

3.application/json

  1. //例子
  2. //传递json
  3.  
  4. POST HTTP/1.1(CRLF)
  5. Host: www.example.com(CRLF)
  6. Content-Type: application/json(CRLF)
  7. Cache-Control: no-cache(CRLF)
  8. Content-Length: 24(CRLF)
  9. (CRLF)
  10. {
  11. "a":1,
  12. "b":"hello"
  13. }

4. multipart/form-data

使用表单上传文件时,必须让 form 的 enctyped 等于这个值。 
并且Http协议会使用boundary来分割上传的参数

  1. //例子
  2. //a="曹",file1是一个文件
  3.  
  4. POST HTTP/1.1(CRLF)
  5. Host: www.example.com(CRLF)
  6. //注意data;和boundary之间有一个空格,并且----WebKitFormBoundary7MA4YWxkTrZu0gW是可以自定义的
  7. Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW(CRLF)
  8. Cache-Control: no-cache(CRLF)
  9. Content-Length: 728
  10. (CRLF)
  11. //如果有Content-Length的话,则Content-Length指下面所有的字节总数,包括boundary
  12. //这里用自定义的boundary来进行分割,注意会在头部加多"--"
  13. ------WebKitFormBoundary7MA4YWxkTrZu0gW(CRLF)
  14. Content-Disposition: form-data; name="a"(CRLF)
  15. (CRLF)
  16. 曹(CRLF)
  17. ------WebKitFormBoundary7MA4YWxkTrZu0gW(CRLF)
  18. Content-Disposition: form-data; name="file1"; filename="1.jpg"
  19. Content-Type: application/octet-stream(CRLF)
  20. (CRLF)
  21. //此处是参数file1 对应的文件的二进制数据
  22. [654dfasalk;af&6…](CRLF)
  23. //最后一个boundary会分别在头部和尾部加多"--"
  24. ------WebKitFormBoundary7MA4YWxkTrZu0gW--(CRLF)

  1. //多个文件同时上传
  1. POST HTTP/1.1(CRLF)
  2. Host: www.example.com(CRLF)
  3. //注意data;和boundary之间有一个空格,并且----WebKitFormBoundary7MA4YWxkTrZu0gW是可以自定义的
  4. Content-Type: multipart/form-data; boundary=---------------------------418888951815204591197893077
  5. Cache-Control: no-cache(CRLF)
  6. Content-Length: 12138(CRLF)
  7. (CRLF)
  8. -----------------------------418888951815204591197893077(CRLF)
  9. // 文件1的头部boundary
  10. Content-Disposition: form-data; name="userfile[]"; filename="文件1.md"(CRLF)
  11. Content-Type: text/markdown(CRLF)
  12. (CRLF)
  13. // 文件1内容开始
  14. // ...
  15. // 文件1内容结束
  16. -----------------------------418888951815204591197893077(CRLF)
  17. // 文件2的头部boundary
  18. Content-Disposition: form-data; name="userfile[]"; filename="文件2"(CRLF)
  19. Content-Type: application/octet-stream(CRLF)
  20. (CRLF)
  21. // 文件2内容开始
  22. // ...
  23. // 文件2内容结束
  24. -----------------------------418888951815204591197893077(CRLF)
  25. // 文件3的头部boundary
  26. Content-Disposition: form-data; name="userfile[]"; filename="文件3"(CRLF)
  27. Content-Type: application/octet-stream(CRLF)
  28. (CRLF)
  29. // 文件3内容开始
  30. // ...
  31. // 文件3内容结束
  32. -----------------------------418888951815204591197893077(CRLF)
  33. // 参数username的头部boundary
  34. Content-Disposition: form-data; name="username"(CRLF)
  35. (CRLF)
  36. zhangsan
  37. -----------------------------418888951815204591197893077(CRLF)
  38. // 参数password的头部boundary
  39. Content-Disposition: form-data; name="password"(CRLF)
  40. (CRLF)
  41. zhangxx
  42. -----------------------------418888951815204591197893077--
  43. // 尾部boundary,表示结束

注意 :(CRLF)\r\n

Android 最早使用的简单的网络请求的更多相关文章

  1. Xamarin.Android之封装个简单的网络请求类

    一.前言 回忆到上篇 <Xamarin.Android再体验之简单的登录Demo> 做登录时,用的是GET的请求,还用的是同步, 于是现在将其简单的改写,做了个简单的封装,包含基于Http ...

  2. 学习RxJava+Retrofit+OkHttp+MVP的网络请求使用

    公司的大佬用的是这一套,那我这个菜鸟肯定要学习使用了. 我在网上找了很多文章,写的都很详细,比如 https://www.jianshu.com/u/5fd2523645da https://www. ...

  3. android通过fiddler代理,抓取网络请求

    安装fiddler过程省略 1, 2, 3, 4,手机需要跟电脑处于同一局域网,设置网络代理为电脑在局域网内的ip,端口为3步设置的port 5,电脑就可以通过fiddler监控手机的所有网络请求了( ...

  4. iOS之ASIHttp简单的网络请求实现

    描述: ASIHttpRequest是应用第三方库的方法,利用代码快,减少代码量,提高效率 准备工作: 一.导入第三方库ASIHttpRequest 二.会报很多的错,原因有两个,一个是要导入Xcod ...

  5. Xamarin 简单的网络请求

    //try            //{            //    var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(re ...

  6. Java笔记7:最简单的网络请求Demo

    一.服务器端 1 新建一个工程,建立一个名为MyRequest的工程. 2 FileàProject StructureàModulesà点击最右侧的“+”àLibraryàJava 找到Tomcat ...

  7. Android之三种网络请求解析数据(最佳案例)

    AsyncTask解析数据 AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法. ...

  8. 基于Retrofit+RxJava的Android分层网络请求框架

    目前已经有不少Android客户端在使用Retrofit+RxJava实现网络请求了,相比于xUtils,Volley等网络访问框架,其具有网络访问效率高(基于OkHttp).内存占用少.代码量小以及 ...

  9. Android 网络请求详解

    我们知道大多数的 Android 应用程序都是通过和服务器进行交互来获取数据的.如果使用 HTTP 协议来发送和接收网络数据,就免不了使用 HttpURLConnection 和 HttpClient ...

随机推荐

  1. 给Array本地对象增加一个原型方法,它用于删除数组条目中重复的条目(可能有多个),返回值是一个包含被删除的重复条目的新数组

    Array.prototype.removeCount=function(){ var that=this; var arr=[]; for(var i=0;i<that.length;i++) ...

  2. [Python] IMG to Char

    Change image into character from PIL import Image import argparse #输入 #命令行输入参数处理 parser = argparse.A ...

  3. svn代码回滚和合并的利器svn merge

    1.svn merge可以将两个对象的diff体现到本地工作目录上. (1)两个对象 这个两个对象可以是同一个svn url的两个revison,也可以是不用的url,比如分支和主干. (2)diff ...

  4. 指向“**js/shop.js”的 <script> 加载失败

    指向“”的 <script> 加载失败 找了半天没找到原因 原来是meta里面的 csp Content-Security-Policy <meta http-equiv=" ...

  5. Notes About Singular Value Decomposition

    A brief summary of SVD: An original matrix Amn is represented as a muliplication of three matrices: ...

  6. VS调试时JSON格式文件无法加载

    VS调试时JSON格式文件无法加载 报错: 解决:在项目中的web.config中进行配置,configuration节中添加以下部份: <system.webServer> <st ...

  7. Arduino教程资料汇总(8月22日悄悄跟新了一下)

    http://www.geek-workshop.com/thread-985-1-1.html 本帖最后由 迷你强 于 2013-8-31 12:36 编辑 =====F-101 arduino基础 ...

  8. iOS开发基础控件--UILabel

    UILabel 的常见属性和方法: //创建UIlabel对象 UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds]; / ...

  9. centos6.5 源码安装 mysql

    1.下载源码包 我的版本:mysql-5.6.4-m7.tar.gz 2.安装之前先卸载CentOS自带的MySQL [root@localhost ~]# yum remove mysql 3.编译 ...

  10. [Unity Shader笔记]渲染路径--Forward渲染路径

    [Unity Shader笔记]渲染路径--Forward渲染路径 (2014-04-22 20:08:25) 转载▼ 标签: shader unity renderingpath forward 游 ...