代码已经上传到github,欢迎Star。
CSDN地址:blog.csdn.net/u010998327/…
一个自己封装的用HttpUrlConnection请求的网络工具类,但只适合新手研究或者做些小demo用下, 毕竟现在对于Android开发的网络框架有很多,而且很好很强大。
- 目前支持的功能:
1、GET,POST请求
2、支持返回String,Byte[]数组,以及自定义的Model类
3、请求的回调已处理过,现在的回调在UI线程,所以可以直接更新UI
同样的,如果写demo啥的,可以按照以下方式依赖进项目:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile 'com.github.MZCretin:HttpUrlConnectionUtilDemo:v1.0'
}
后面如果有需要,我会加上下载文件的方法。
如果有啥问题,欢迎交流:
792075058
mxnzp_life@163.com
正文
最近吃腻了外卖,想着自己做饭吃,所以就自己做了一个菜谱的小软件,从api服务上找了一个菜谱的接口就开始做了,在做的过程中,需要请求一个接口,来获取菜谱信息,于是就想到Android现在很火的各种网络框架。。。在选择的时候就犯难了,我就写个软件自己用,就简单的请求一个接口,有必要用这么重的框架么。然后就开始了主题所说的自定义一个简单的网络加载工具类。
我这边只是做了一个简单的封装。
首先:定义一个 static ExecutorService threadPool = Executors.newCachedThreadPool(),来创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。因为不能在主线程请求网络,所以用这个线程池来装载我们用于进行网络请求的线程,定义一个static Gson gson = new Gson();用来将请求的json数据转换成对应的Model对象。
然后:定义第一个方法,也就是返回字符串的方法。在这个方法里,上面有关HttpURLConnection的操作都是一样的,不一样的是最后对流的处理,这个方法要求返回的是字符串,所以我们在获取到流的时候将其转化成我们需要的字符串,再通过回调给调用者,其他goGet方法也一样,如果需要byte数组,我们就返回byte数组,如果需要对象,我们就先转成String字符串,然后通过gson将json字符串转换成对应的对象返回即可。(具体请看源码,下面会贴出源码)
doGet方法
/** * GET方法 返回数据会解析成字符串String * @param context 上下文 * @param urlString 请求的url * @param listener 回调监听 */
public static void doGet(final Context context, final String urlString, final HttpCallbackStringListener listener) {
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
// 根据URL地址创建URL对象
url = new URL(urlString);
// 获取HttpURLConnection对象
httpURLConnection = ( HttpURLConnection ) url.openConnection();
// 设置请求方式,默认为GET
httpURLConnection.setRequestMethod("GET");
// 设置连接超时
httpURLConnection.setConnectTimeout(5000);
// 设置读取超时
httpURLConnection.setReadTimeout(8000);
// 响应码为200表示成功,否则失败。
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = "";
while ( (line = bf.readLine()) != null ) {
buffer.append(line);
}
bf.close();
is.close();
new ResponseCall(context, listener).doSuccess(buffer.toString());
} else {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 释放资源
httpURLConnection.disconnect();
}
}
}
});
}
上面讲了doGet方法的实现,其实doPost方法的实现除了需要带上参数列表之外其他都是是一样的。对于参数的处理,在我的开发经历中,参数都是放在Map容器中传递的,所以在这里也就使用的这种方式,对于传进来的参数,我们需要进行处理下,其实也就是字符串的拼接,拼接成HttpURLConnection能够识别的形式。下面的代码进行了参数的组织:
final StringBuffer out = new StringBuffer();
// 组织请求参数
for (String key : params.keySet()) {
if(out.length()!=0){
out.append("&");
}
out.append(key).append("=").append(params.get(key));
}
拼接好参数列表之后,我们通过httpURLConnection.getOutputStream()获取到PrintWriter,然后写入我们的参数信息即可。其他的操作跟get请求是一样的。
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(out.toString());
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
doPost方法
/** * POST方法 返回数据会解析成字符串 String * @param context 上下文 * @param urlString 请求的路径 * @param listener 回调监听 * @param params 参数列表 */
public static void doPost(final Context context, final String urlString, final HttpCallbackStringListener listener, final Map<String, Object> params) {
final StringBuffer out = new StringBuffer();
// 组织请求参数
for (String key : params.keySet()) {
if(out.length()!=0){
out.append("&");
}
out.append(key).append("=").append(params.get(key));
}
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urlString);
httpURLConnection = ( HttpURLConnection ) url.openConnection();
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Content-Length", String
.valueOf(out.length()));
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(8000);
// 设置运行输入
httpURLConnection.setDoInput(true);
// 设置运行输出
httpURLConnection.setDoOutput(true);
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(out.toString());
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = "";
while ( (line = bf.readLine()) != null ) {
buffer.append(line);
}
bf.close();
is.close();
new ResponseCall(context, listener).doSuccess(buffer.toString());
} else {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 最后记得关闭连接
httpURLConnection.disconnect();
}
}
}
});
}
在上面的代码中,在请求的最后,我们会看到一个 new ResponseCall(context, listener).doSuccess(buffer.toString());这个是用来干嘛的呢?其实这个是用来进行子线程和主线程的数据交换的,定义一个Handler,不过Handler是通过looper来创建的,looper是通过传进来的上下文Context来获取主线程的looper,然后次Handler就是位于主线程的。当请求结束后,如果请求成功,则调用doSuccess(T response)方法,给Handler发送消息,消息的what值为0,消息的内容是请求的结果;请求失败或错误的时候,调用doFail(Exception e)方法,给Handler发送消息,消息的what值为1,消息的内容是请求失败的异常信息。当Handler收到消息之后,直接调用listener的回调方法,就可以一方面把数据回调回去,另一方面,回调也是处于主线程也就是UI线程了,这样调用者就可以直接在回调方法中更新UI了。
ResponseCall.java
/** * Created by cretin on 2017/3/20. */
public class ResponseCall<T> {
//用于在子线程和主线程的数据交换
Handler mHandler;
public ResponseCall(Context context, final HttpCallbackModelListener listener) {
Looper looper = context.getMainLooper();
mHandler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if ( msg.what == 0 ) {
//成功
listener.onFinish(msg.obj);
} else if ( msg.what == 1 ) {
//失败
listener.onError(( Exception ) msg.obj);
}
}
};
}
public ResponseCall(Context context, final HttpCallbackBytesListener listener) {
Looper looper = context.getMainLooper();
mHandler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if ( msg.what == 0 ) {
//成功
listener.onFinish(( byte[] ) msg.obj);
} else if ( msg.what == 1 ) {
//失败
listener.onError(( Exception ) msg.obj);
}
}
};
}
public ResponseCall(Context context, final HttpCallbackStringListener listener) {
Looper looper = context.getMainLooper();
mHandler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if ( msg.what == 0 ) {
//成功
listener.onFinish(msg.obj.toString());
} else if ( msg.what == 1 ) {
//失败
listener.onError(( Exception ) msg.obj);
}
}
};
}
public void doSuccess(T response) {
Message message = Message.obtain();
message.obj = response;
message.what = 0;
mHandler.sendMessage(message);
}
public void doFail(Exception e) {
Message message = Message.obtain();
message.obj = e;
message.what = 1;
mHandler.sendMessage(message);
}
}
下面是实际中的调用实例:
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.cretin.www.httpurlconnectionutil.HttpUtils;
import com.cretin.www.httpurlconnectionutil.callback.HttpCallbackBytesListener;
import com.cretin.www.httpurlconnectionutil.callback.HttpCallbackModelListener;
import com.cretin.www.httpurlconnectionutil.callback.HttpCallbackStringListener;
import com.cretin.www.httpurlconnectionutildemo.model.ResponseModel;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tvContent = ( TextView ) findViewById(R.id.tv_content);
//测试GET请求
//返回字符串
try {
HttpUtils.doGet(this, "http://caipu.yjghost.com/index.php/query/read?menu=" + URLEncoder.encode("土豆", "UTF-8") + "&rn=15&start=1", new HttpCallbackStringListener() {
@Override
public void onFinish(String response) {
tvContent.setText(response);
}
@Override
public void onError(Exception e) {
tvContent.setText(e.toString());
}
});
} catch ( UnsupportedEncodingException e ) {
e.printStackTrace();
}
//返回byte数组
try {
HttpUtils.doGet(this, "http://caipu.yjghost.com/index.php/query/read?menu=" + URLEncoder.encode("土豆", "UTF-8") + "&rn=15&start=1", new HttpCallbackBytesListener() {
@Override
public void onFinish(byte[] response) {
Log.e("HHHHHHH", "GET 方法:" + new String(response));
}
@Override
public void onError(Exception e) {
Log.e("HHHHHHH", "doGet onError:" + e.toString());
}
});
} catch ( UnsupportedEncodingException e ) {
e.printStackTrace();
}
//返回对象
try {
HttpUtils.doGet(this, "http://caipu.yjghost.com/index.php/query/read?menu=" +
URLEncoder.encode("土豆", "UTF-8") + "&rn=15&start=1",
new HttpCallbackModelListener<ResponseModel>() {
@Override
public void onFinish(ResponseModel response) {
Log.e("HHHHHHH", "GET 方法:" + response.getResult().getTotalNum());
}
@Override
public void onError(Exception e) {
Log.e("HHHHHHH", "doGet onError:" + e.toString());
}
}, ResponseModel.class);
} catch ( UnsupportedEncodingException e ) {
e.printStackTrace();
}
//测试POST请求
//参数列表
Map<String, Object> map = new HashMap<>();
map.put("productFirstType", "1");
map.put("loanRange", "1");
map.put("type", "hot");
map.put("page", "1");
map.put("timeRange", "1");
//返回String
HttpUtils.doPost(this, "http://101.201.31.212:8016/product/listProduct", new HttpCallbackStringListener() {
@Override
public void onFinish(String response) {
Log.e("HHHHHHH", "POST 方法:" + response);
}
@Override
public void onError(Exception e) {
Log.e("HHHHHHH", "doPost onError:" + e.toString());
}
}, map);
//返回byte数组
HttpUtils.doPost(this, "http://101.201.31.212:8016/product/listProduct", new HttpCallbackBytesListener() {
@Override
public void onFinish(byte[] response) {
Log.e("HHHHHHH", "POST 方法:" + new String(response));
}
@Override
public void onError(Exception e) {
Log.e("HHHHHHH", "doPost onError:" + e.toString());
}
}, map);
//返回对象
HttpUtils.doPost(this, "http://101.201.31.212:8016/product/listProduct", new HttpCallbackModelListener<ResponseModel>() {
@Override
public void onFinish(ResponseModel response) {
Log.e("HHHHHHH", "POST 方法:" + response.getResult().getTotalNum());
}
@Override
public void onError(Exception e) {
Log.e("HHHHHHH", "doPost onError:" + e.toString());
}
}, map, ResponseModel.class);
}
}
下面贴出整个工具类的代码:
import android.accounts.NetworkErrorException;
import android.content.Context;
import com.cretin.www.httpurlconnectionutil.callback.HttpCallbackBytesListener;
import com.cretin.www.httpurlconnectionutil.callback.HttpCallbackModelListener;
import com.cretin.www.httpurlconnectionutil.callback.HttpCallbackStringListener;
import com.cretin.www.httpurlconnectionutil.response.ResponseCall;
import com.google.gson.Gson;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** * Created by cretin on 2017/3/22. * HttpURLConnection 网络请求工具类 * * 数据的请求都是基于HttpURLConnection的 请求成功与失败的回调都是在主线程 * 可以直接更新UI */
public class HttpUtils {
static ExecutorService threadPool = Executors.newCachedThreadPool();
static Gson gson = new Gson();
/** * GET方法 返回数据会解析成字符串String * @param context 上下文 * @param urlString 请求的url * @param listener 回调监听 */
public static void doGet(final Context context, final String urlString, final HttpCallbackStringListener listener) {
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
// 根据URL地址创建URL对象
url = new URL(urlString);
// 获取HttpURLConnection对象
httpURLConnection = ( HttpURLConnection ) url.openConnection();
// 设置请求方式,默认为GET
httpURLConnection.setRequestMethod("GET");
// 设置连接超时
httpURLConnection.setConnectTimeout(5000);
// 设置读取超时
httpURLConnection.setReadTimeout(8000);
// 响应码为200表示成功,否则失败。
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = "";
while ( (line = bf.readLine()) != null ) {
buffer.append(line);
}
bf.close();
is.close();
new ResponseCall(context, listener).doSuccess(buffer.toString());
} else {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 释放资源
httpURLConnection.disconnect();
}
}
}
});
}
/** * GET方法 返回数据会解析成byte[]数组 * @param context 上下文 * @param urlString 请求的url * @param listener 回调监听 */
public static void doGet(final Context context, final String urlString, final HttpCallbackBytesListener listener) {
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url = null;
HttpURLConnection httpURLConnection = null;
try {
// 根据URL地址创建URL对象
url = new URL(urlString);
// 获取HttpURLConnection对象
httpURLConnection = ( HttpURLConnection ) url.openConnection();
// 设置请求方式,默认为GET
httpURLConnection.setRequestMethod("GET");
// 设置连接超时
httpURLConnection.setConnectTimeout(5000);
// 设置读取超时
httpURLConnection.setReadTimeout(8000);
// 响应码为200表示成功,否则失败。
if ( httpURLConnection.getResponseCode() != 200 ) {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
} else {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
// 读取输入流中的数据
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ( (len = bis.read(bytes)) != -1 ) {
baos.write(bytes, 0, len);
}
bis.close();
is.close();
// 响应的数据
new ResponseCall(context, listener).doSuccess(baos.toByteArray());
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 释放资源
httpURLConnection.disconnect();
}
}
}
});
}
/** * GET方法 返回数据会解析成cls对象 * @param context 上下文 * @param urlString 请求路径 * @param listener 回调监听 * @param cls 返回的对象 * @param <T> 监听的泛型 */
public static <T> void doGet(final Context context, final String urlString, final HttpCallbackModelListener listener, final Class<T> cls) {
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
// 根据URL地址创建URL对象
url = new URL(urlString);
// 获取HttpURLConnection对象
httpURLConnection = ( HttpURLConnection ) url.openConnection();
// 设置请求方式,默认为GET
httpURLConnection.setRequestMethod("GET");
// 设置连接超时
httpURLConnection.setConnectTimeout(5000);
// 设置读取超时
httpURLConnection.setReadTimeout(8000);
// 响应码为200表示成功,否则失败。
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = "";
while ( (line = bf.readLine()) != null ) {
buffer.append(line);
}
bf.close();
is.close();
new ResponseCall(context, listener).doSuccess(gson.fromJson(buffer.toString(), cls));
} else {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 释放资源
httpURLConnection.disconnect();
}
}
}
});
}
/** * POST方法 返回数据会解析成字符串 String * @param context 上下文 * @param urlString 请求的路径 * @param listener 回调监听 * @param params 参数列表 */
public static void doPost(final Context context, final String urlString, final HttpCallbackStringListener listener, final Map<String, Object> params) {
final StringBuffer out = new StringBuffer();
// 组织请求参数
for (String key : params.keySet()) {
if(out.length()!=0){
out.append("&");
}
out.append(key).append("=").append(params.get(key));
}
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urlString);
httpURLConnection = ( HttpURLConnection ) url.openConnection();
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Content-Length", String
.valueOf(out.length()));
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(8000);
// 设置运行输入
httpURLConnection.setDoInput(true);
// 设置运行输出
httpURLConnection.setDoOutput(true);
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(out.toString());
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = "";
while ( (line = bf.readLine()) != null ) {
buffer.append(line);
}
bf.close();
is.close();
new ResponseCall(context, listener).doSuccess(buffer.toString());
} else {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 最后记得关闭连接
httpURLConnection.disconnect();
}
}
}
});
}
/** * POST方法 返回数据会解析成Byte[]数组 * @param context 上下文 * @param urlString 请求的路径 * @param listener 回调监听 * @param params 参数列表 */
public static void doPost(final Context context, final String urlString, final HttpCallbackBytesListener listener, final Map<String, Object> params) {
final StringBuffer out = new StringBuffer();
// 组织请求参数
for (String key : params.keySet()) {
if(out.length()!=0){
out.append("&");
}
out.append(key).append("=").append(params.get(key));
}
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urlString);
httpURLConnection = ( HttpURLConnection ) url.openConnection();
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Content-Length", String
.valueOf(out.length()));
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(8000);
// 设置运行输入
httpURLConnection.setDoInput(true);
// 设置运行输出
httpURLConnection.setDoOutput(true);
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(out.toString());
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
// 读取输入流中的数据
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ( (len = bis.read(bytes)) != -1 ) {
baos.write(bytes, 0, len);
}
bis.close();
is.close();
// 响应的数据
new ResponseCall(context, listener).doSuccess(baos.toByteArray());
} else {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 最后记得关闭连接
httpURLConnection.disconnect();
}
}
}
});
}
/** * /** * POST方法 返回数据会解析成cls对象 * @param context 上下文 * @param urlString 请求的路径 * @param listener 回调监听 * @param params 参数列表 * @param cls 对象 * @param <T> 监听泛型 */
public static <T> void doPost(final Context context, final String urlString, final HttpCallbackModelListener listener, final Map<String, Object> params, final Class<T> cls) {
final StringBuffer paramsStr = new StringBuffer();
// 组织请求参数
Iterator it = params.entrySet().iterator();
while ( it.hasNext() ) {
Map.Entry element = ( Map.Entry ) it.next();
paramsStr.append(element.getKey());
paramsStr.append("=");
paramsStr.append(element.getValue());
paramsStr.append("&");
}
if ( paramsStr.length() > 0 ) {
paramsStr.deleteCharAt(paramsStr.length() - 1);
}
// 因为网络请求是耗时操作,所以需要另外开启一个线程来执行该任务。
threadPool.execute(new Runnable() {
@Override
public void run() {
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urlString);
httpURLConnection = ( HttpURLConnection ) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(8000);
// 设置运行输入
httpURLConnection.setDoInput(true);
// 设置运行输出
httpURLConnection.setDoOutput(true);
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(paramsStr.toString());
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
if ( httpURLConnection.getResponseCode() == 200 ) {
// 获取网络的输入流
InputStream is = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//最好在将字节流转换为字符流的时候 进行转码
StringBuffer buffer = new StringBuffer();
String line = "";
while ( (line = bf.readLine()) != null ) {
buffer.append(line);
}
bf.close();
is.close();
new ResponseCall(context, listener).doSuccess(gson.fromJson(buffer.toString(), cls));
} else {
new ResponseCall(context, listener).doFail(
new NetworkErrorException("response err code:" +
httpURLConnection.getResponseCode()));
}
} catch ( MalformedURLException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} catch ( IOException e ) {
if ( listener != null ) {
// 回调onError()方法
new ResponseCall(context, listener).doFail(e);
}
} finally {
if ( httpURLConnection != null ) {
// 最后记得关闭连接
httpURLConnection.disconnect();
}
}
}
});
}
}
HttpCallbackBytesListener.java
/** * HttpURLConnection网络请求返回监听器 */
public interface HttpCallbackBytesListener {
// 网络请求成功
void onFinish(byte[] response);
// 网络请求失败
void onError(Exception e);
}
HttpCallbackModelListener.java
/** * HttpURLConnection网络请求返回监听器 */
public interface HttpCallbackModelListener<T> {
// 网络请求成功
void onFinish(T response);
// 网络请求失败
void onError(Exception e);
}
HttpCallbackStringListener.java
/** * HttpURLConnection网络请求返回监听器 */
public interface HttpCallbackStringListener {
// 网络请求成功
void onFinish(String response);
// 网络请求失败
void onError(Exception e);
}
代码已经上传到github,欢迎Star。
我叫Cretin,一个可爱的小男孩。