网络请求封装类lmxHttpUrlConnection

来源:互联网 发布:太平洋下载中心软件. 编辑:程序博客网 时间:2024/06/05 11:37

  由于android在api23及以上的版本中废弃了httpclient,所以用了之前lmxHttpClient同样的方法,将请求完成的业务逻辑抽象后封装了httpUrlConnection,方式是一样的。

  虽然也可以在高于23的版本下继续使用httpclient,方式见http://blog.csdn.net/u014727233/article/details/51985429,不过早晚还是要换的吧,以下个人代码,错误之处望指正

  工具类lmxHttpUrlConnection的代码如下

lmxHttpUrlConnection:

package com.newbest.smarthome.androidtest0802_not_important;import android.util.Log;import java.io.BufferedOutputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import java.util.HashMap;import java.util.Iterator;import java.util.Set;/** * Created by limengxiao on 16/8/2. */public abstract class lmxHttpUrlConnection {    //    time out value in milliseconds    public static final int TIME_OUT = 5000;    //    Basic request address    public static String URL_STR;    //    Encoding type in this request,such as "utf-8"    public static String ENCODING;    //    Request data in form of string    // such as "username=limengxiao&password=123456"    public static String DATA_STR;    //    Constructor can either use DATA_STR or DATA_MAP as data resource    //    if no data resource is needed,use "" or null instead    public lmxHttpUrlConnection(String basicUrl, String encoding, String dataStr) {        this.URL_STR = basicUrl;        this.ENCODING = encoding;        if (dataStr == null || dataStr == "") {            this.DATA_STR = null;        } else {            this.DATA_STR = dataStr;        }    }    //    Request data in form of hashmap    // for example the hashmap has called "hashmap.put("username","limengxiao")" and "hashmap.put("username","limengxiao")"    public lmxHttpUrlConnection(String basicUrl, String encoding, HashMap<String, String> dataMap) {        this.URL_STR = basicUrl;        this.ENCODING = encoding;        try {            this.DATA_STR = getFormedDataString(dataMap);        } catch (UnsupportedEncodingException e) {            Log.i("res", "lmx:encoding error occurs when encoding the specified encoding type to the value of the dataMap");            e.printStackTrace();        }    }    public String getFormedDataString(HashMap<String, String> map) throws UnsupportedEncodingException {        if (map == null) {            return null;        } else {            Set<String> keySet = map.keySet();            if (keySet.size() == 0) {                return null;            }            Iterator<String> it = keySet.iterator();            StringBuilder sb = new StringBuilder();            while (it.hasNext()) {                String keyStr = it.next();                Log.i("res", "keyStr-->" + keyStr);                String valStr = map.get(keyStr);                Log.i("res", "valStr-->" + valStr);//            Format encoding of the value                valStr = URLEncoder.encode(valStr, ENCODING);                sb.append(keyStr + "=" + valStr + "&");            }//            Remove last '&',if exists            Log.i("res", "line 78,sb.toString()-->" + sb.toString());            String lastChar = sb.charAt(sb.length() - 1) + "";            if (lastChar.equals("&")) {                sb.deleteCharAt(sb.length() - 1);            }            Log.i("res", "data String-->" + sb.toString());            return sb.toString();        }    }    public abstract void onSuccess(String resultStr);    public abstract void onFailure(String errorStr);    public void doPost() {        new Thread() {            @Override            public void run() {                try {                    URL url = new URL(URL_STR);                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();//                          To upload data to a web server, configure the connection for output using setDoOutput(true).                    connection.setDoOutput(true);                    connection.setDoInput(true);                    connection.setChunkedStreamingMode(0);                    connection.setRequestMethod("POST");                    connection.setUseCaches(false);                    connection.setConnectTimeout(TIME_OUT);                    connection.setReadTimeout(TIME_OUT);                    connection.setRequestProperty("Accept_Encoding", ENCODING);                    connection.setRequestProperty("Connection", "keep-alive");                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                    if (DATA_STR != null) {                        connection.setRequestProperty("Content-Length", String.valueOf(DATA_STR.getBytes().length));                    }                    OutputStream out = new BufferedOutputStream(connection.getOutputStream());                    out.write(DATA_STR.getBytes());                    out.flush();                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {                        InputStream is = connection.getInputStream();                        ByteArrayOutputStream baos = new ByteArrayOutputStream();                        int lenth = 0;                        byte buffer[] = new byte[1024];                        while ((lenth = is.read(buffer)) != -1) {                            baos.write(buffer, 0, lenth);                        }                        is.close();                        baos.close();                        String resultStr = new String(baos.toByteArray());                        onSuccess(resultStr);                    } else {                        onSuccess("请求返回数据状态吗不是200(请求失败)");                    }                } catch (MalformedURLException e) {                    e.printStackTrace();                    Log.i("res", "lmx:-->Url Error,type-->MalformedURLException,info-->" + e.toString());                    onFailure(e.toString());                } catch (IOException e) {                    e.printStackTrace();                    Log.i("res", "lmx:-->IOException,info" + e.toString());                    onFailure(e.toString());                }            }        }.start();    }    public void doGet() {        new Thread() {            @Override            public void run() {                HttpURLConnection connection = null;                try {                    String basicUrlStr = URL_STR;//                  Open to enable auto add "?" to basic url in get methods//                  In get method,If the url string does not have a "?" at the end of the string,add a "?"                    /*if (!basicUrlStr.endsWith("?")) {                        basicUrlStr += "?";                    }*/                    if (DATA_STR != null) {                        basicUrlStr += DATA_STR;                    }                    Log.i("res", "Full url of GET request:-->\n" + basicUrlStr);                    URL url = new URL(basicUrlStr);                    connection = (HttpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setReadTimeout(TIME_OUT);                    connection.setConnectTimeout(TIME_OUT);                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {                        InputStream is = connection.getInputStream();                        ByteArrayOutputStream baos = new ByteArrayOutputStream();                        int len = 0;                        byte buffer[] = new byte[1024];                        while ((len = is.read(buffer)) != -1) {                            baos.write(buffer, 0, len);                        }                        is.close();                        baos.close();                        String resultStr = new String(baos.toByteArray());                        onSuccess(resultStr);                    } else {//                  The resoponseCode is not 200                        onFailure("lmx,getMethod,onFailure-->the return code is-->" + connection.getResponseCode());                    }                } catch (Exception e) {                    e.printStackTrace();                    Log.i("res", "lmx:url parse error,info-->" + e.toString());                    onFailure("lmx:url parse error,info-->" + e.toString());                }            }        }.start();    }    ;}

使用方式与之前我封装的lmxHttpclient基本一样,区别在于这次代码可以允许不带参数的get/post请求

MainActivity部分代码:

post部分,使用公司内网的请求地址

String url = "http://192.168.1.188:80/login";                HashMap<String, String> map = new HashMap<String, String>();                map.put("username", "admin");                map.put("password", "123456");                lmxHttpUrlConnection postConn = new lmxHttpUrlConnection(url, "utf-8", map) {                    @Override                    public void onSuccess(String resultStr) {                        Log.i("res", "请求成功,返回字符串-->\n" + resultStr);                    }                    @Override                    public void onFailure(String errorStr) {                        Log.i("res", "请求失败,返回字符串-->" + errorStr);                    }                };                postConn.doPost();

get部分,使用心知天气接口(聚合审核没通过,暂时用下这个)

HashMap<String, String> xzMap = new HashMap<String, String>();                xzMap.put("key", "这里是我的key");                xzMap.put("location", "shanghai");                xzMap.put("language", "zh-Hans");                xzMap.put("unit", "c");                lmxHttpUrlConnection getConn = new lmxHttpUrlConnection(BASIC_URL_XINZHI, "utf-8", xzMap) {                    @Override                    public void onSuccess(String resultStr) {                        Log.i("res", "请求成功-->" + resultStr);                    }                    @Override                    public void onFailure(String errorStr) {                        Log.i("res", "请求失败-->" + errorStr);                    }                };                getConn.doGet();

以上,不用在工作线程中调用,抽象方法onSuccess/onFailure也不用runOnUiThread(),这些都在doGet()、doPost()里写好了

运行结果

公司内网post返回值






测试运行通过 2016.8.2


0 0
原创粉丝点击