无论是post还是get,http请求实际上直到HttpURLConnection.getInputStream()这个函数里面才正式发送出去。
直接上代码
HttpConnectHelper核心功能类
</pre><span style="font-size:14px;"></span><pre name="code" class="java"><span style="font-size:14px;">import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.util.Log;
/**
* 进行网络连接助手类
* @author Jim
*
*/
public class HttpConnectHelper {
public static final String TAG = "HttpConnectHelper";
public <span style="font-family:Arial;"><span style="line-height: 21px;"><span style="font-size:12px;">volatile</span><span style="font-size: 14px;"> </span></span></span>static final int HTTP_GET = 1;
public static final int HTTP_POST = 2;
public static HttpConnectHelper connectHelper;
//线程池
private ExecutorService mExecutorService;
/**
* 获取单例的HttpConnectHelper
* @return HttpConnectHelper实例
*/
public static HttpConnectHelper getHttpConnectHelper(){
if(connectHelper == null){
<span style="white-space:pre"> </span><pre name="code" class="java"><span style="white-space:pre"> </span>synchronized(<span style="font-family: Arial, Helvetica, sans-serif;">HttpConnectHelper</span>.class){
if(
connectHelper == null){
connectHelper = new HttpConnectHelper();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}
return connectHelper;
}
/**
* 获取线程池的方法
* 加锁
* @return ExecutorService实例
*/
public ExecutorService getThreadPool(){
if(mExecutorService == null){
synchronized(ExecutorService.class){
if(mExecutorService == null){
//限制为最多三条线程
mExecutorService = Executors.newFixedThreadPool(3);
}
}
}
return mExecutorService;
}
/**
* 发送http请求
* (默认为get请求)
* @param httpMethod 发送请求的方式(HttpConnectHelper.HTTP_GET,HttpConnectHelper.HTTP_POST)
* @param url 请求的url
* @param arr 请求参数
* @param listener 请求回调接口
*/
public void doSendRequest(final int httpMethod, final String url,final Map<String,String> arr, final HttpResponseListener listener ){
getThreadPool().execute(new Runnable() {
@Override
public void run() {
Log.e(TAG, url);
HttpURLConnection httpURLConnection = null;
if(url == null) return ;
try {
URL httpUrl = new URL(url);
//建立连接
httpURLConnection = (HttpURLConnection)httpUrl.openConnection();
//设置参数
httpURLConnection.setReadTimeout(10*1000);
httpURLConnection.setConnectTimeout(10*1000);
httpURLConnection.setDoInput(true);
//httpURLConnection.setRequestProperty("Content-Type","application/json;charset=utf-8".replaceAll("\\s", ""));
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
switch(httpMethod){
case HTTP_GET:
Log.e(TAG, "----------doGet");
httpURLConnection.setRequestMethod("GET");
break;
case HTTP_POST:
Log.e(TAG, "----------doPost");
httpURLConnection.setRequestMethod("POST");
//添加参数
String params = appendParams(arr);
Log.e(TAG, params);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDefaultUseCaches(false);
httpURLConnection.setRequestProperty("Content-Length",String.valueOf(params.length()));
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
printWriter.print(params);
printWriter.flush();
printWriter.close();
break;
}
//处理输入流
//判断处理结果
//Log.e(TAG, "-------------code : " + httpURLConnection.getResponseCode());
if(httpURLConnection.getResponseCode() == 200){
listener.onfinishResponse(handleInput(httpURLConnection.getInputStream()));
}else{
listener.onfinishResponseError(handleInput(httpURLConnection.getErrorStream()));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* 工具方法,拼接参数
* @param params post参数
* @return
* @throws UnsupportedEncodingException
*/
public String appendParams(Map<String, String> params) throws UnsupportedEncodingException{
StringBuffer parmasStr = new StringBuffer();
HashMap<String, String> map = (HashMap<String, String>)params;
if(params == null) return null;
int i = 0;
Iterator<String> iterator = map.keySet().iterator();
String key;
String value;
while(iterator.hasNext()){
if(i != 0){
parmasStr.append("&");
}
key = iterator.next();
value = map.get(key);
//转码,以防中文乱码
//不转码会出现超时现象
parmasStr.append(key).append("=").append(URLEncoder.encode(value, "utf-8"));
i++;
}
return parmasStr.toString();
}
/**
* 工具方法,用于处理输入流
* @param input 输入流
* @return 处理后的String
*/
public String handleInput(InputStream input){
if(input == null ) return null;
BufferedInputStream inputStream = new BufferedInputStream(input);
StringBuffer responseStr = new StringBuffer();
byte []data = new byte[1024];
int length = 0;
try {
while((length = inputStream.read(data)) != -1){
responseStr.append(new String(data, 0, length, "utf-8"));
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(inputStream != null){
try {
inputStream.close();
if(input != null){
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseStr.toString();
}
public synchronized void cancalTask(){
if(mExecutorService != null){
mExecutorService.shutdown();
mExecutorService = null;
}
}
}</span>
<span style="font-size:14px;">
</span>
<span style="font-size:14px;">package com.jim.http.util;
/**
* 相应接口,回调响应返回
* @author Administrator
*
*/
public interface HttpResponseListener {
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//返回出错时回调
<span style="white-space:pre"> </span>public void onfinishResponseError(String response);
<span style="white-space:pre"> </span>//返回成功时回调
<span style="white-space:pre"> </span>public void onfinishResponse(String response);
}
</span>
</pre><pre name="code" class="java">
<span style="font-size:24px;color:#ff0000;"><strong>测试代码</strong></span>
package com.jim.http.test;import java.util.HashMap;
import com.example.httppoj.R;
import com.jim.http.util.HttpConnectHelper;
import com.jim.http.util.HttpResponseListener;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class TestActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
//发送POST请求
//-------------------------------------------------------------------
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "Jim");
map.put("age", "22");
HttpConnectHelper.getHttpConnectHelper().doSendRequest(
HttpConnectHelper.HTTP_POST,
"http://10.21.20.108:80/my.php",
map,
new HttpResponseListener() {
@Override
public void onfinishResponseError(String response) {
Log.w("TestActivity",response);
}
@Override
public void onfinishResponse(String response) {
Log.w("TestActivity",response);
}
});
//--------------------------------------------------------------------
//发送GET请求
//-------------------------------------------------------------------
HttpConnectHelper.getHttpConnectHelper().doSendRequest(
HttpConnectHelper.HTTP_POST,
"http://10.21.20.108:80/my.php",
new HashMap<String, String>(),
new HttpResponseListener() {
@Override
public void onfinishResponseError(String response) {
Log.w("TestActivity",response);
}
@Override
public void onfinishResponse(String response) {
Log.w("TestActivity",response);
}
});
//---------------------------------------------------------------------
}
}