Android 最早使用的简单的网络请求

时间:2021-11-18 17:03:32

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

 import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map; import org.apache.http.entity.mime.content.FileBody; import android.util.Log; public class HttpRequest { public static final String UTF_8 = "UTF-8"; private static String cookie = null; /**
* GET请求
*
* @param actionUrl
* @param params
* @return
*/
public static String httpGet(String actionUrl, Map<String, String> params) {
try{
StringBuffer urlbuff = new StringBuffer(actionUrl);
if (params != null && params.size() > 0) {
if (actionUrl.indexOf("?") >= 0) {
urlbuff.append("&");
} else {
urlbuff.append("?");
}
for (String key : params.keySet()) {
urlbuff.append(key).append("=").append(URLEncoder.encode(params.get(key), UTF_8)).append("&");
}
urlbuff.deleteCharAt(urlbuff.length() - 1);
Log.v("---request---Get---", urlbuff.toString());
}
URL url = new URL(urlbuff.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);// 允许输入
conn.setDoOutput(false);// 允许输出
conn.setUseCaches(false);// 不使用Cache
conn.setRequestMethod("GET");
conn.setRequestProperty("Charset", UTF_8);
if (cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
int cah = conn.getResponseCode();
if (cah != 200)
throw new RuntimeException("请求url失败");
if (conn.getHeaderField("Set-Cookie") != null) {
cookie = conn.getHeaderField("Set-Cookie");
}
Log.i("", "------------------cookie:" + cookie);
Map<String, List<String>> keys = conn.getHeaderFields();
for(String key : keys.keySet()) {
List<String> list = keys.get(key);
for(String value : list) {
Log.i("", "header: key:" + key + " values:" + value);
}
} InputStream is = conn.getInputStream();
int ch;
StringBuilder b = new StringBuilder();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
is.close();
conn.disconnect();
return b.toString();
}catch(Exception e) {
e.printStackTrace();
}
return null;
} /**
* post 带文件上传
* @param actionUrl
* @param params
* @param files
* @return
*/
public static String httpPost(String actionUrl, Map<String, String> params, Map<String, FileBody> files) {
String LINE_START = "--";
String LINE_END = "\r\n";
String BOUNDRY = "*****"; try{
HttpURLConnection conn = null;
DataOutputStream dos = null; int bytesRead, bytesAvailable, bufferSize;
long totalBytes;
byte[] buffer;
int maxBufferSize = 8096; URL url = new URL(actionUrl);
conn = (HttpURLConnection) url.openConnection(); // Allow Inputs
conn.setDoInput(true); // Allow Outputs
conn.setDoOutput(true); // Don't use a cached copy.
conn.setUseCaches(false); // Use a post method.
conn.setRequestMethod("POST");
//if (files != null && files.size() > 0) {
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
//} Log.i("", "cookie:" + cookie);
if (cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
// // Set the cookies on the response
// String cookie = CookieManager.getInstance().getCookie(server);
// if (cookie != null) {
// conn.setRequestProperty("Cookie", cookie);
// } // // Should set this up as an option
// if (chunkedMode) {
// conn.setChunkedStreamingMode(maxBufferSize);
// } dos = new DataOutputStream(conn.getOutputStream()); // Send any extra parameters
for (Object key : params.keySet()) {
dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"" + LINE_END);
dos.writeBytes(LINE_END);
dos.write(params.get(key).getBytes());
dos.writeBytes(LINE_END); Log.i("", "-----key:" + key + " value:" + params.get(key));
}
//-----------
if (files != null && files.size() > 0) {
for (String key : files.keySet()) {
Log.i("", "-----key:" + key + " value:" + params.get(key));
FileBody fileBody = files.get(key);
dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\";" + " filename=\"" + fileBody.getFilename() +"\"" + LINE_END);
dos.writeBytes("Content-Type: " + fileBody.getMimeType() + LINE_END);
dos.writeBytes(LINE_END); // Get a input stream of the file on the phone
InputStream fileInputStream = new FileInputStream(fileBody.getFile());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytes = 0;
while (bytesRead > 0) {
totalBytes += bytesRead;
//result.setBytesSent(totalBytes);
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(LINE_END);
// close streams
fileInputStream.close();
}
}
dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);
dos.flush();
dos.close(); int statusCode = conn.getResponseCode();
Log.i("", "---------------statusCode:" + statusCode);
if (statusCode != 200) {
throw new HttpRequestException("server error");
} //------------------ read the SERVER RESPONSE
InputStream is = conn.getInputStream();
int ch;
StringBuilder b = new StringBuilder();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
conn.disconnect(); return b.toString();
}catch(Exception e){
Log.i("", "---------------" + e.getMessage(), e.fillInStackTrace());
e.printStackTrace();
}
return null;
} /**
* post请求
* @param actionUrl
* @param params
* @return
*/
public static String httpPost(String actionUrl, Map<String, String> params){
try{
URL url = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//因为这个是post请求,设立需要设置为true
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置以POST方式
conn.setRequestMethod("POST");
// Post 请求不能使用缓存
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
if (cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
conn.connect();
//DataOutputStream流
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
//要上传的参数
StringBuffer content = new StringBuffer();
for (String key : params.keySet()) {
//String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
content.append(key).append("=").append(params.get(key)).append("&");
}
//将要上传的内容写入流中
out.writeBytes(content.toString());
//刷新、关闭
out.flush();
out.close(); int statusCode = conn.getResponseCode();
Log.i("", "---------------statusCode:" + statusCode);
if (statusCode != 200) {
throw new HttpRequestException("server error");
}
if (conn.getHeaderField("Set-Cookie") != null) {
cookie = conn.getHeaderField("Set-Cookie");
}
//获取数据
InputStream is = conn.getInputStream();
int ch;
StringBuilder b = new StringBuilder();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
conn.disconnect();
return b.toString();
}catch(Exception e) {
Log.i("", "---------------" + e.getMessage(), e.fillInStackTrace());
e.printStackTrace();
}
return null;
} }

1. application/x-www-form-urlencoded

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

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

2. text/xml

 //例子

 POST http://www.example.com HTTP/1.1(CRLF)
Content-Type: text/xml(CRLF)
(CRLF)
<?xml version="1.0"?>
<resource>
<id>123</id>
<params>
<name>
<value>homeway</value>
</name>
<age>
<value>22</value>
</age>
</params>
</resource>

3.application/json

 //例子
//传递json POST HTTP/1.1(CRLF)
Host: www.example.com(CRLF)
Content-Type: application/json(CRLF)
Cache-Control: no-cache(CRLF)
Content-Length: 24(CRLF)
(CRLF)
{
"a":1,
"b":"hello"
}

4. multipart/form-data

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

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

//多个文件同时上传
 POST  HTTP/1.1(CRLF)
Host: www.example.com(CRLF)
//注意data;和boundary之间有一个空格,并且----WebKitFormBoundary7MA4YWxkTrZu0gW是可以自定义的
Content-Type: multipart/form-data; boundary=---------------------------418888951815204591197893077
Cache-Control: no-cache(CRLF)
Content-Length: 12138(CRLF)
(CRLF)
-----------------------------418888951815204591197893077(CRLF)
// 文件1的头部boundary
Content-Disposition: form-data; name="userfile[]"; filename="文件1.md"(CRLF)
Content-Type: text/markdown(CRLF)
(CRLF)
// 文件1内容开始
// ...
// 文件1内容结束
-----------------------------418888951815204591197893077(CRLF)
// 文件2的头部boundary
Content-Disposition: form-data; name="userfile[]"; filename="文件2"(CRLF)
Content-Type: application/octet-stream(CRLF)
(CRLF)
// 文件2内容开始
// ...
// 文件2内容结束
-----------------------------418888951815204591197893077(CRLF)
// 文件3的头部boundary
Content-Disposition: form-data; name="userfile[]"; filename="文件3"(CRLF)
Content-Type: application/octet-stream(CRLF)
(CRLF)
// 文件3内容开始
// ...
// 文件3内容结束
-----------------------------418888951815204591197893077(CRLF)
// 参数username的头部boundary
Content-Disposition: form-data; name="username"(CRLF)
(CRLF)
zhangsan
-----------------------------418888951815204591197893077(CRLF)
// 参数password的头部boundary
Content-Disposition: form-data; name="password"(CRLF)
(CRLF)
zhangxx
-----------------------------418888951815204591197893077--
// 尾部boundary,表示结束

注意 :(CRLF)\r\n