記錄一下HttpURLConnection的基本使用
package com.xuegu.max_library.util;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpClientUtils {
private static final String TAG = "HttpClientUtils";
public static void get(final String requestUrl, final HttpClientUtils.OnRequestCallBack callBack) {
new Thread() {
public void run() {
getRequest(requestUrl, callBack);
}
}.start();
}
public static void post(final String requestUrl, final String params, final HttpClientUtils.OnRequestCallBack callBack) {
new Thread() {
public void run() {
postRequest(requestUrl, params, callBack);
}
}.start();
}
private static void getRequest(String requestUrl, HttpClientUtils.OnRequestCallBack callBack) {
boolean isSuccess = false;
String message;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設定請求的方法爲"POST",默認是GET
connection.setRequestMethod("GET");
connection.setConnectTimeout(50000);
connection.setReadTimeout(50000);
// User-Agent IE9的標識
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;");
connection.setRequestProperty("Accept-Language", "zh-CN");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
/*
* 當我們要獲取我們請求的http地址訪問的數據時就是使用connection.getInputStream().read()方式時我們就需要setDoInput(true),
* 根據api文檔我們可知doInput默認就是爲true。我們可以不用手動設置了,如果不需要讀取輸入流的話那就setDoInput(false)。
* 當我們要採用非get請求給一個http網絡地址傳參 就是使用connection.getOutputStream().write() 方法時我們就需要setDoOutput(true), 默認是false
*/
// 設置是否從httpUrlConnection讀入,默認情況下是true;
connection.setDoInput(true);
// 設置是否向httpUrlConnection輸出,如果是post請求,參數要放在http正文內,因此需要設爲true, 默認是false;
//connection.setDoOutput(true);//Android 4.0 GET時候 用這句會變成POST 報錯java.io.FileNotFoundException
connection.setUseCaches(false);
connection.connect();//
int contentLength = connection.getContentLength();
Log.i("k開始讀取數據","數據長度"+contentLength);
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();//會隱式調用connect()
baos = new ByteArrayOutputStream();
int readLen;
byte[] bytes = new byte[1024];
while ((readLen = inputStream.read(bytes)) != -1) {
baos.write(bytes, 0, readLen);
}
Log.i("數據讀取完成","數據長度"+contentLength);
String result = baos.toString();
Log.i("數據讀取完成","數據爲"+result);
// XLogUtils.i(TAG, " result:" + result);
message = result;
isSuccess = true;
} else {
message = "請求失敗 code:" + connection.getResponseCode();
}
} catch (MalformedURLException e) {
message = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
message = e.getMessage();
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
message = e.getMessage();
e.printStackTrace();
}
}
if (isSuccess) {
callBack.onSuccess(message);
} else {
callBack.onError(message);
}
}
private static void postRequest(String requestUrl, String params, HttpClientUtils.OnRequestCallBack callBack) {
boolean isSuccess = false;
String message;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設定請求的方法爲"POST",默認是GET
connection.setRequestMethod("POST");
connection.setConnectTimeout(50000);
connection.setReadTimeout(50000);
// User-Agent IE9的標識
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;");
connection.setRequestProperty("Accept-Language", "zh-CN");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
/*
* 當我們要獲取我們請求的http地址訪問的數據時就是使用connection.getInputStream().read()方式時我們就需要setDoInput(true),
* 根據api文檔我們可知doInput默認就是爲true。我們可以不用手動設置了,如果不需要讀取輸入流的話那就setDoInput(false)。
* 當我們要採用非get請求給一個http網絡地址傳參 就是使用connection.getOutputStream().write() 方法時我們就需要setDoOutput(true), 默認是false
*/
// 設置是否從httpUrlConnection讀入,默認情況下是true;
connection.setDoInput(true);
// 設置是否向httpUrlConnection輸出,如果是post請求,參數要放在http正文內,因此需要設爲true, 默認是false;
connection.setDoOutput(true);
connection.setUseCaches(false);
// // 現將參數寫入緩衝區等待發送
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), “UTF-8”);
// 發送請求params參數
out.write(params);
out.flush();
connection.connect();//這個時候纔是真正的將參數發送給服務器的時候.
int contentLength = connection.getContentLength();
if (connection.getResponseCode() == 200) {
// 會隱式調用connect()
inputStream = connection.getInputStream();
baos = new ByteArrayOutputStream();
int readLen;
byte[] bytes = new byte[1024];
while ((readLen = inputStream.read(bytes)) != -1) {
baos.write(bytes, 0, readLen);
}
String backStr = baos.toString();
// XLogUtils.i(TAG, “backStr:” + backStr);
message = backStr;
isSuccess = true;
} else {
message = "請求失敗 code:" + connection.getResponseCode();
}
} catch (MalformedURLException e) {
message = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
message = e.getMessage();
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
message = e.getMessage();
e.printStackTrace();
}
}
if (isSuccess) {
callBack.onSuccess(message);
} else {
callBack.onError(message);
}
}
public interface OnRequestCallBack {
void onSuccess(String json);
void onError(String errorMsg);
}
}