上面是最新的
package com.android.mall.net;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.android.mall.tool.Loger;
public class HTTP {
/**
* 返回请求网络字符串数据
*
* @param url
* 请求地址
* @param params
* 请求参数
* @param method
* 请求方法
* @return 字符串数据
*/
public static String getString(String url, Map<String, String> params, String method) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if (params != null && params.size() > 0) {
Iterator<String> iterator = params.keySet().iterator();
List<BasicNameValuePair> requestParam = new ArrayList<BasicNameValuePair>();
String param = "";
String value = "";
while (iterator.hasNext()) {
param = iterator.next();
value = params.get(param);
requestParam.add(new BasicNameValuePair(param, value));
}
post.setEntity(new UrlEncodedFormEntity(requestParam, "UTF-8"));
}
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
Loger.e("Http Error", e);
}
return null;
}
/**
* 使用 HttpURLConnection Get方法请求网络返回网络流
*
* @param urlStr
* 请求地址
* @return 网络流
*/
public static InputStream httpGet(String urlStr) {
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Charsert", "UTF-8");
connection.setConnectTimeout(1000 * 20);
connection.setReadTimeout(1000 * 20);
connection.setRequestMethod("GET");
if (connection.getResponseCode() != HttpStatus.SC_OK) {
return null;
}
InputStream inStream = connection.getInputStream();
if (inStream != null) {
return inStream;
}
} catch (Exception e) {
Loger.e("HttpGet error", e);
return null;
}
return null;
}
}