Android客户端使用HTTP通信
Android作为客户端(client)对服务器(server)进行request操作,并从服务器中得到response。
这里主要使用HTTP来进行数据传输,request有GET和POST两种方式。
完整的项目:https://github.com/lijiancheng0614/android-NetworkConnect
注意
以下代码可以检测网络是否连接,但不包括hotspot的连接。
1 | /** |
代码
RequestTask类封装了AsyncTask,实现了异步通信等细节。
RequestTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117package com.example.android.networkconnect;
import android.os.AsyncTask;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Implementation of AsyncTask, to fetch the data in the background away from the UI thread.
*/
public class RequestTask extends AsyncTask<String, Void, String> {
public static final String TAG = "RequestTask";
private static final int CONNECT_TIMEOUT = 15000 /* milliseconds */;
private static final int BUFFER_SIZE = 32;
private boolean isPost = false;
/**
* Set POST method.
*
* @param isPost true if post.
*/
public void setPost(boolean isPost) {
this.isPost = isPost;
}
protected String doInBackground(String... strings) {
try {
String result = "";
HttpURLConnection conn;
if (isPost) {
conn = doPost(strings[0], strings[1]);
} else {
conn = doGet(strings[0]);
}
// Success HTTP Status Code
if (conn.getResponseCode() / 100 != 2)
return result;
result = getStringFromStream(conn.getInputStream());
return result;
} catch (IOException e) {
return e.getLocalizedMessage();
}
}
/**
* Given a string representation of a URL, sets up a connection for GET request.
*
* @param urlString A string representation of a URL.
* @return A HttpURLConnection.
* @throws java.io.IOException
*/
private HttpURLConnection doGet(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
return conn;
}
/**
* Given a string representation of a URL, sets up a connection for POST request.
*
* @param urlString A string representation of a URL.
* @param postData Post data.
* @return A HttpURLConnection.
* @throws java.io.IOException
*/
private HttpURLConnection doPost(String urlString, String postData) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length()));
DataOutputStream dataOutputStream = null;
try {
dataOutputStream = new DataOutputStream(conn.getOutputStream());
dataOutputStream.writeBytes(postData);
} finally {
if (dataOutputStream != null)
dataOutputStream.close();
}
return conn;
}
/**
* Reads an InputStream and converts it to a String.
*
* @param inputStream InputStream.
* @return String from inputStream.
* @throws java.io.IOException
*/
private String getStringFromStream(InputStream inputStream) throws IOException {
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
StringBuilder sb = new StringBuilder(BUFFER_SIZE);
char[] buffer = new char[BUFFER_SIZE];
int length;
while ((length = isr.read(buffer, 0, BUFFER_SIZE)) != -1) {
sb.append(buffer, 0, length);
if (isCancelled())
return null;
}
inputStream.close();
isr.close();
return sb.toString();
}
}