欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android封装的http请求实用工具类

程序员文章站 2023-11-18 12:25:16
复制代码 代码如下:import java.io.bufferedreader;import java.io.inputstreamreader;import java.n...


复制代码 代码如下:

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;

               

       
    }
}