Android封装的http请求实用工具类
脚本之家 / 编程助手:解决程序员“几乎”所有问题!
脚本之家官方知识库 → 点击立即使用
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
/**
* 网络工具类
*
* @author malinkang
*
*/
public class NetUtils {
/**
* 对网络连接状态进行判断
*
* @return true, 可用; false, 不可用
*/
public static boolean isOpenNetwork(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connManager.getActiveNetworkInfo() != null) {
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
/**
* get请求
*
* @param urlString
* @param params
* @return
*/
public static String getRequest(String urlString, Map<String, String> params) {
try {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(urlString);
if (null != params) {
urlBuilder.append("?");
Iterator<Entry<String, String>> iterator = params.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
urlBuilder
.append(URLEncoder.encode(param.getKey(), "UTF-8"))
.append('=')
.append(URLEncoder.encode(param.getValue(), "UTF-8"));
if (iterator.hasNext()) {
urlBuilder.append('&');
}
}
}
// 创建HttpClient对象
HttpClient client = getNewHttpClient();
// 发送get请求创建HttpGet对象
HttpGet getMethod = new HttpGet(urlBuilder.toString());
HttpResponse response = client.execute(getMethod);
// 获取状态码
int res = response.getStatusLine().getStatusCode();
if (res == 200) {
StringBuilder builder = new StringBuilder();
// 获取响应内容
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader
.readLine()) {
builder.append(s);
}
return builder.toString();
}
} catch (Exception e) {
}
return null;
}
/**
* post请求
*
* @param urlString
* @param params
* @return
*/
public static String postRequest(String urlString,
List<BasicNameValuePair> params) {
try {
// 1. 创建HttpClient对象
HttpClient client = getNewHttpClient();
// 2. 发get请求创建HttpGet对象
HttpPost postMethod = new HttpPost(urlString);
postMethod.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = client.execute(postMethod);
int statueCode = response.getStatusLine().getStatusCode();
if (statueCode == 200) {
System.out.println(statueCode);
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
}
return null;
}
// 保存时+当时的秒数,
public static long expires(String second) {
Long l = Long.valueOf(second);
return l * 1000L + System.currentTimeMillis();
}
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
另一种封装好的get请求,最近经常用的:
public class HttpUtils {
private final static String TAG = "EasyTokenSevice";
private final static int connectionTimeout = 5000;
private static InputStream inputStream = null;
private static String urlStr = null;
private static boolean isConnecting;
/**
* 封装http get请求
*
* @param url
* @return is
*/
public static InputStream get(String url)throws IOException ,Exception {
urlStr = url;
isConnecting = true;
HttpGet httpGet = new HttpGet(urlStr);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
connectionTimeout);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
return inputStream;}
else return null;
}
}
微信公众号搜索 “ 脚本之家 ” ,选择关注
程序猿的那些事、送书等活动等着你
相关文章
Anroid ListView分组和悬浮Header实现方法
这篇文章主要介绍了Anroid ListView分组和悬浮Header实现方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2016-11-11ListView上滑和下滑,显示和隐藏Toolbar的实现方法
下面小编就为大家分享一篇ListView上滑和下滑,显示和隐藏Toolbar的实现方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-01-01Android开发之图形图像与动画(一)Paint和Canvas类学习
Paint类代表画笔,用来描述图形的颜色和风格,如线宽,颜色,透明度和填充效果等信息;Canvas类代表画布,通过该类提供的构造方法,可以绘制各种图形;感兴趣的朋友可以了解下啊,希望本文对你有所帮助2013-01-01android studio git 删除已在远程仓库的文件或文件夹方式
这篇文章主要介绍了android studio git 删除已在远程仓库的文件或文件夹方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-04-04
最新评论