博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android 封装http请求的工具类
阅读量:6274 次
发布时间:2019-06-22

本文共 5503 字,大约阅读时间需要 18 分钟。

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
params) { try { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(urlString); if (null != params) { urlBuilder.append("?"); Iterator
> iterator = params.entrySet() .iterator(); while (iterator.hasNext()) { Entry
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
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(); } }}

转载地址:http://sprpa.baihongyu.com/

你可能感兴趣的文章
Item 23 不要在代码中使用新的原生态类型(raw type)
查看>>
为网页添加留言功能
查看>>
JavaScript—数组(17)
查看>>
Android 密钥保护和 C/S 网络传输安全理论指南
查看>>
以太坊ERC20代币合约优化版
查看>>
Why I Began
查看>>
同一台电脑上Windows 7和Ubuntu 14.04的CPU温度和GPU温度对比
查看>>
js数组的操作
查看>>
springmvc Could not write content: No serializer
查看>>
Python系语言发展综述
查看>>
新手 开博
查看>>
借助开源工具高效完成Java应用的运行分析
查看>>
163 yum
查看>>
第三章:Shiro的配置——深入浅出学Shiro细粒度权限开发框架
查看>>
80后创业的经验谈(转,朴实但实用!推荐)
查看>>
让Windows图片查看器和windows资源管理器显示WebP格式
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
vim使用点滴
查看>>
embedded linux学习中几个需要明确的概念
查看>>