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;

}
}

时间: 2024-09-21 14:22:10

Android封装的http请求实用工具类的相关文章

分页封装实用工具类及其使用方法

分页封装实用工具类及其使用方法 作者: javaboy2012 Email:yanek@163.com qq:    1046011462     package com.yanek.util; import java.util.List; public class PageBean { /** * @param args */ public static void main(String[] args) { } private int currentpage; // 当前页数 private

Pig系统分析(7) Pig实用工具类

Explain Explain是Pig提供的调试工具,使用explain可以输出Pig Lation的执行计划.值得一提的是,explain支持-dot选项,将执行计划以DOT格式输出, (DOT是一种图形描述语言,请参考http://zh.wikipedia.org/zh/DOT%E8%AF%AD%E8%A8%80) 代码实现详见org.apache.pig.impl.plan.DotPlanDumper,这部分实现为我们设计执行计划可视化提供了参考. 下图部分截取了使用Graphviz打开物

CLHep 2.1.1.0发布 实用工具类

CLHep是一套HEP特定的基础库和实用工具类,如随机生成器,物理向量,几何,和线性代数.CLHep是由一个独立于任何外部的程序包构成,即允许在一定条件下CLHEP的相互依存关系). CLHep 2.1.1.0版本增加了一个Azzalini歪斜正态分布的实施,修复了一些小的bug. 软件信息:http://wwwasd.web.cern.ch/wwwasd/lhc++/clhep/ 下载地址: Source: http://wwwasd.web.cern.ch/wwwasd/lhc++/clhe

http接口开发请求参数签名实用工具类

作用: 在http接口对参数做签名,防止接口被非法调用    package com.yanek.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.ArrayList; import java

轻松把玩HttpClient之封装HttpClient工具类(六),封装输入参数,简化工具类

       在写这个工具类的时候发现传入的参数太多,以至于方法泛滥,只一个send方法就有30多个,所以对工具类进行了优化,把输入参数封装在一个对象里,这样以后再扩展输入参数,直接修改这个类就ok了.        不多说了,先上代码: /** * 请求配置类 * * @author arron * @date 2016年2月2日 下午3:14:32 * @version 1.0 */ public class HttpConfig { private HttpConfig(){}; /**

翻翻git之---实用工具类Lazy(绝对的好东西,走过路过别错过)

转载请注明出处:这里写链接内容 今天还是继续昨天的从Git上找点"有用的","好玩的","推荐的"东西给大家,今天贴的是一个工具类.地址如下https://github.com/ddwhan0123/Lazy 原作者Blog:http://weibo.com/2675061813/profile?topnav=1&wvr=6 他有一些比较常用的,诸如设备状态啊,土司啊,窗口啊,测量啊什么的,还有些我觉得平时回去搜,但是不多的资源,如拼音和

自己封装的poi操作Excel工具类

       在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类.        该工具类主要完成的功能是:读取Excel.汇总Excel的功能.在读取时,可以设定开始和结束读取的位置.设定是否读取多个sheet.设定读取那个或者那些sheet等.在汇总时,如设定是否覆盖目标文件.设定是否比较检查重复内容.设定检查重复的列索引等功能.具体来演示一下吧:        工具类源码: package com.tgb.

android实用工具类分享(获取内存/检查网络/屏幕高度/手机分辨率)

复制代码 代码如下:public class CommonUtil { public static boolean hasSDCard() { String status = Environment.getExternalStorageState();  return status.equals(Environment.MEDIA_MOUNTED); } /**  * 获取最大内存  *   * @return  */ public static long getMaxMemory() { re

android开发教程之实现toast工具类_Android

Android中不用再每次都写烦人的Toast了,直接调用这个封装好的类,就可以使用了! 复制代码 代码如下: package com.zhanggeng.contact.tools; /** * Toasttool can make you  use Toast more easy ;  *  * @author ZHANGGeng * @version v1.0.1 * @since JDK5.0 * */import android.content.Context;import andro