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;

}
}

(0)

相关推荐

  • android 一些工具类汇总

    一 Paint ,Canvas public class drawView extends View{ private Paint paint1; public drawView(Context context,AttributeSet set ){ super(context,set); } public void onDraw(Canvas canvas){ super.onDraw(canvas); //new 一个画笔对象 paint1= new Paint(); canvas.draw

  • 19个Android常用工具类汇总

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.PreferencesUtils.JSONUtils.FileUtils.ResourceUtils.StringUtils.ParcelUtils.RandomUtils.ArrayUtils.ImageUtils.ListUtils.MapUtils.ObjectUtils.SerializeUtils.

  • 实例详解Android快速开发工具类总结

    一.日志工具类 Log.java public class L { private L() { /* 不可被实例化 */ throw new UnsupportedOperationException("Cannot be instantiated!"); } // 是否需要打印bug,可以在application的onCreate函数里面初始化 public static boolean isDebug = true; private static final String TAG

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

    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

  • Android AES加密工具类分享

    1.AES加密工具类 java不支持PKCS7Padding,只支持PKCS5Padding.我们知道加密算法由算法+模式+填充组成,下一篇介绍iOS和Android通用的AES加密,本篇文章使用PKCS5Padding加密方式. package com.example.aesdemo; import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.SecretK

  • android自动工具类TextUtils使用详解

    今天,简单讲讲如何使用android自动的工具类TextUtils. 简单列举部分用法: Log.d(TAG, "---------------------------------"); //字符串拼接 Log.d(TAG, TextUtils.concat("Hello", " ", "world!").toString()); //判断是否为空字符串 Log.d(TAG, TextUtils.isEmpty("H

  • Android7.0 工具类:DiffUtil详解

    一 概述 DiffUtil是support-v7:24.2.0中的新工具类,它用来比较两个数据集,寻找出旧数据集->新数据集的最小变化量. 说到数据集,相信大家知道它是和谁相关的了,就是我的最爱,RecyclerView. 就我使用的这几天来看,它最大的用处就是在RecyclerView刷新时,不再无脑mAdapter.notifyDataSetChanged(). 以前无脑mAdapter.notifyDataSetChanged()有两个缺点: 1.不会触发RecyclerView的动画(删

  • Android 数据存储之 FileInputStream 工具类及FileInputStream类的使用

    安卓的三种本地的典型数据存储方式 SharedPreferences 以文件格式保存在本地存储中 SQL数据库 这篇文章就是讲解一下如何使用 SharedPreferences 保存文件.主要解释什么都写在注释里面的. IDE : Android Studio 参考文章:http://www.jb51.net/article/74215.htm 絮叨一下:本来文件操作这一块上周就想把其弄懂,然后继续进一步的学习.但是因为官方的 Android Training 之中的概念太过于繁杂.导致我认为存

  • Android屏幕分辨率工具类使用详解

    Android开发中我们经常需要用到将dip.px相互换算.获取手机屏幕的宽度.高度以及状态栏高度等,如下是基于屏幕这一块整理的一个类. package com.per.loadingwebviewdome; import android.content.Context; import android.util.DisplayMetrics; import java.lang.reflect.Field; /** * @author: xiaolijuan * @description: 屏幕分

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

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

随机推荐