1 关键知识点
1 HttpURLConnection 接口
URL url = new URL("IP地址");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection()
2 设置HttpURLConnection 属性,比如设置输入输出流,传输方式,是否使用缓存等
2 逻辑代码
1 打开连接,
2 设置连接属性
3 获取数据流或发送数据流
4 对数据流进行处理
5 关闭数据流
3 JDK
01
public String executeHttpGet() {
02
String result = null;
03
URL url = null;
04
HttpURLConnection connection = null;
05
InputStreamReader in = null;
06
try {
07
url = new URL("http://10.0.2.2:8888/data/get/?token=alexzhou");
08
connection = (HttpURLConnection) url.openConnection();
09
in = new InputStreamReader(connection.getInputStream());
10
BufferedReader bufferedReader = new BufferedReader(in);
11
StringBuffer strBuffer = new StringBuffer();
12
String line = null;
13
while ((line = bufferedReader.readLine()) != null) {
14
strBuffer.append(line);
15
}
16
result = strBuffer.toString();
17
} catch (Exception e) {
18
e.printStackTrace();
19
} finally {
20
if (connection != null) {
21
connection.disconnect();
22
}
23
if (in != null) {
24
try {
25
in.close();
26
} catch (IOException e) {
27
e.printStackTrace();
28
}
29
}
30
31
}
32
return result;
33
}
01
public String executeHttpPost() {
02
String result = null;
03
URL url = null;
04
HttpURLConnection connection = null;
05
InputStreamReader in = null;
06
try {
07
url = new URL("http://10.0.2.2:8888/data/post/");
08
connection = (HttpURLConnection) url.openConnection();
09
connection.setDoInput(true);
10
connection.setDoOutput(true);
11
connection.setRequestMethod("POST");
12
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
13
connection.setRequestProperty("Charset", "utf-8");
14
DataOutputStream dop = new DataOutputStream(
15
connection.getOutputStream());
16
dop.writeBytes("token=alexzhou");
17
dop.flush();
18
dop.close();
19
20
in = new InputStreamReader(connection.getInputStream());
21
BufferedReader bufferedReader = new BufferedReader(in);
22
StringBuffer strBuffer = new StringBuffer();
23
String line = null;
24
while ((line = bufferedReader.readLine()) != null) {
25
strBuffer.append(line);
26
}
27
result = strBuffer.toString();
28
} catch (Exception e) {
29
e.printStackTrace();
30
} finally {
31
if (connection != null) {
32
connection.disconnect();
33
}
34
if (in != null) {
35
try {
36
in.close();
37
} catch (IOException e) {
38
e.printStackTrace();
39
}
40
}
41
42
}
43
return result;
44
}
APACHE
01
public String executeGet() {
02
String result = null;
03
BufferedReader reader = null;
04
try {
05
HttpClient client = new DefaultHttpClient();
06
HttpGet request = new HttpGet();
07
request.setURI(new URI(
08
"http://10.0.2.2:8888/data/get/?token=alexzhou"));
09
HttpResponse response = client.execute(request);
10
reader = new BufferedReader(new InputStreamReader(response
11
.getEntity().getContent()));
12
13
StringBuffer strBuffer = new StringBuffer("");
14
String line = null;
15
while ((line = reader.readLine()) != null) {
16
strBuffer.append(line);
17
}
18
result = strBuffer.toString();
19
20
} catch (Exception e) {
21
e.printStackTrace();
22
} finally {
23
if (reader != null) {
24
try {
25
reader.close();
26
reader = null;
27
} catch (IOException e) {
28
e.printStackTrace();
29
}
30
}
31
}
32
33
return result;
34
}
01
public String executePost() {
02
String result = null;
03
BufferedReader reader = null;
04
try {
05
HttpClient client = new DefaultHttpClient();
06
HttpPost request = new HttpPost();
07
request.setURI(new URI("http://10.0.2.2:8888/data/post/"));
08
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
09
postParameters.add(new BasicNameValuePair("token", "alexzhou"));
10
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
11
postParameters);
12
request.setEntity(formEntity);
13
14
HttpResponse response = client.execute(request);
15
reader = new BufferedReader(new InputStreamReader(response
16
.getEntity().getContent()));
17
18
StringBuffer strBuffer = new StringBuffer("");
19
String line = null;
20
while ((line = reader.readLine()) != null) {
21
strBuffer.append(line);
22
}
23
result = strBuffer.toString();
24
25
} catch (Exception e) {
26
e.printStackTrace();
27
} finally {
28
if (reader != null) {
29
try {
30
reader.close();
31
reader = null;
32
} catch (IOException e) {
33
e.printStackTrace();
34
}
35
}
36
}
37
38
return result;
39
}
相关类参考
package com.android.lxcrm.util;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.os.Handler;
import com.android.lxcrm.util.MMultipartEntity.ProgressListener;
/**
* TODO
*/
public class HttpConnection {
static final String TAG = "HttpConnection";
/*
* do post 方式
*/
/**
* 以post方式请求服务,设置相关的请求参数
*
* @param homeUrl
* @param params
* @param enc
* @return
* @throws Exception
*/
public static String httpDoPostByMapParams(Context mContext,
String homeUrl, Map<String, Object> params) throws Exception {
StringBuffer sb = new StringBuffer();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey()).append('=').append(entry.getValue())
.append('&');
}
sb.deleteCharAt(sb.length() - 1);
}
URL url = new URL(homeUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置提交方式
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
// post方式不能使用缓存
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
// 设置连接超时时间
conn.setConnectTimeout(25 * 1000);
// 配置本次连接的Content-Type,配置为application/x-www-form-urlencoded
// conn.setRequestProperty("Content-Type",
// "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置浏览器编码
conn.setRequestProperty("Charset", "UTF-8");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// 将请求参数数据向服务器端发送
dos.writeChars(sb.toString());
dos.flush();
dos.close();
if (conn.getResponseCode() == 200) {
byte[] data = FileUtil.readInputStream(conn.getInputStream());
return new String(data);
} else {
int errorCode = conn.getResponseCode();
return null;
}
}
/**
* HTTP DOPOST httpClient
*/
public static String httpDoPostByMapParams(Context mContext,
String homeUrl, Map<String, Object> params, String tag,
String filePath) throws Exception {
HttpClient httpClient;
HttpPost httpPost;
MultipartEntity mpEntity = new MultipartEntity();
String ret = null;
HttpParams httpparms = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparms, 25 * 1000);
HttpConnectionParams.setSoTimeout(httpparms, 25 * 1000);
httpClient = new DefaultHttpClient(httpparms);
httpPost = new HttpPost(homeUrl);
if (params != null && !params.isEmpty()) {
for (Entry<String, Object> entry : params.entrySet()) {
mpEntity.addPart(entry.getKey(),
new StringBody((String) (entry.getValue() == null ? ""
: entry.getValue()), Charset.forName("UTF-8")));
}
}
if (filePath != null && !"".equals(filePath)) {
mpEntity.addPart(tag, new FileBody(new File(filePath)));
}
LogHelper.i("homeUrl-->" + homeUrl);
try {
httpPost.setEntity(mpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(httpResponse.getEntity());
} else {
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/*
* 多参数传递
*/
// //队列执行
public static String httpDoPostByMapParams2(Context mContext,
String homeUrl, String... params) throws Exception {
HttpClient httpClient;
HttpPost httpPost;
MultipartEntity mpEntity = new MultipartEntity();
String ret = null;
HttpParams httpparms = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparms, 25 * 1000);
HttpConnectionParams.setSoTimeout(httpparms, 25 * 1000);
httpClient = new DefaultHttpClient(httpparms);
httpPost = new HttpPost(homeUrl);
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i += 2) {
mpEntity.addPart(params[i], new StringBody(
(String) (params[i + 1] == null ? "" : params[i + 1]),
Charset.forName("UTF-8")));
}
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < params.length; i++) {
sb.append(params[i] + "&");
}
LogHelper.i("homeUrl2-->" + homeUrl);
LogHelper.i("params-->" + sb.toString());
try {
httpPost.setEntity(mpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(httpResponse.getEntity());
} else {
LogHelper.e(TAG, "访问错误--"
+ httpResponse.getStatusLine().getStatusCode());
LogHelper
.e(TAG,
"访问错误--"
+ EntityUtils.toString(httpResponse
.getEntity()));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 以普通的带参数的方式请求http 服务
*
* @param mainUrl
* 不带参数的 主url地址
* @param paramsList
* 参数列表
* @return 返回响应的字符串
*/
public static String HttpDoPostByValuePair(Context mContext,
String homeUrl, List<NameValuePair> paramsList) {
try {
BasicNameValuePair nameValuePair1 = new BasicNameValuePair(
"source", "1000");
BasicNameValuePair nameValuePair2 = new BasicNameValuePair(
"status", "1000");
HttpPost httpPost = new HttpPost(homeUrl);
httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
HttpResponse Response = new DefaultHttpClient().execute(httpPost);
if (Response.getStatusLine().getStatusCode() == 200) // 状态码
{
String result = EntityUtils.toString(Response.getEntity());
return result;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//
public static String httpGetByMapParams(Context mContext, String homeUrl,
Map<String, Object> params) throws Exception {
StringBuilder sb = new StringBuilder(homeUrl);
sb.append('?');
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey())
.append('=')
.append(URLEncoder.encode(entry.getValue().toString(),
"UTF-8")).append('&');
}
}
sb.deleteCharAt(sb.length() - 1);
URL url = new URL(sb.toString());
LogHelper.i("请求地址-->" + sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(25 * 1000);
conn.setReadTimeout(25 * 1000);
// conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
if (conn.getResponseCode() == 200) {
byte[] data = FileUtil.readInputStream(conn.getInputStream());
return new String(data);
} else {
}
return null;
}
public static String httpGetByMapParams(Context mContext, String homeUrl,
Map<String, Object> params, boolean gzip) throws Exception {
StringBuilder sb = new StringBuilder(homeUrl);
sb.append('?');
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey())
.append('=')
.append(URLEncoder.encode(entry.getValue().toString(),
"UTF-8")).append('&');
}
}
sb.deleteCharAt(sb.length() - 1);
URL url = new URL(sb.toString());
LogHelper.i("请求地址-->" + sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(25 * 1000);
conn.setReadTimeout(25 * 1000);
conn.setRequestProperty("Accept-Encoding", "gzip");
conn.setRequestProperty("Accept-Charset", "utf-8");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
is = new GZIPInputStream(is);
byte[] data = FileUtil.readInputStream(is);
return new String(data, "UTF-8");
} else {
}
return null;
}
public static String uploadFile(Context mContext, String homeUrl,
Map<String, String> params, String filetag, final File file) {
long start = System.currentTimeMillis();
HttpClient httpClient;
HttpPost httpPost;
MMultipartEntity mpEntity = new MMultipartEntity(
new ProgressListener() {
@Override
public void transferred(long num) {
}
});
try {
HttpParams httpparms = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparms, 25 * 1000);
HttpConnectionParams.setSoTimeout(httpparms, 25 * 1000);
httpClient = new DefaultHttpClient(httpparms);
httpPost = new HttpPost(homeUrl);
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
mpEntity.addPart(
entry.getKey(),
new StringBody(entry.getValue() == null ? ""
: entry.getValue(), Charset
.forName("UTF-8")));
}
}
if (file != null) {
mpEntity.addPart(filetag, new FileBody(file));
}
httpPost.setEntity(mpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
long end = System.currentTimeMillis();
LogHelper.i("Http响应时间---% " + (end - start) + " 毫秒" + " %"
+ (end - start) / 1000f + " 秒");
return EntityUtils.toString(httpResponse.getEntity());
} else {
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String uploadFile(Context mContext, String homeUrl,
Map<String, String> params, String filetag, final File file,
final String path, final Handler mHandler) {
long start = System.currentTimeMillis();
HttpClient httpClient;
HttpPost httpPost;
MMultipartEntity mpEntity = new MMultipartEntity(
new MMultipartEntity.ProgressListener() {
@Override
public void transferred(long num) {
}
});
try {
HttpParams httpparms = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparms, 25 * 1000);
HttpConnectionParams.setSoTimeout(httpparms, 25 * 1000);
httpClient = new DefaultHttpClient(httpparms);
httpPost = new HttpPost(homeUrl);
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
mpEntity.addPart(
entry.getKey(),
new StringBody(entry.getValue() == null ? ""
: entry.getValue(), Charset
.forName("UTF-8")));
}
}
if (file != null) {
mpEntity.addPart(filetag, new FileBody(file));
}
httpPost.setEntity(mpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
long end = System.currentTimeMillis();
LogHelper.i("Http响应时间---% " + (end - start) + " 毫秒" + " %"
+ (end - start) / 1000f + " 秒");
return EntityUtils.toString(httpResponse.getEntity());
} else {
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}