Android http https訪問網路及資源

來源:互聯網
上載者:User

標籤:

Http

private String getHttpValue() {        String str="";        String url = "http://test";        URL getUrl;        HttpURLConnection connection;        try {            getUrl = new URL(url);            connection = (HttpURLConnection) getUrl.openConnection();            connection.connect();            BufferedReader reader = new BufferedReader(new InputStreamReader(                    connection.getInputStream()));            String lines;            while ((lines = reader.readLine()) != null) {                 str+=lines;            }            reader.close();            connection.disconnect();        } catch (MalformedURLException e1) {            e1.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        System.out.println("請求返回內容:\n" + str.toString());                if (str != "") {            try {                JSONObject jsonObject = new JSONObject(str);                str = jsonObject.getString("key");            } catch (Exception e) {                Log.e(TAG, e.toString());            }        }        return str;    }
http擷取網路Json參數
private void setHttpImage() {        ImageView image = null;        try {            Log.i(TAG, "http協議準備擷取網路頭像資源...");            globalInfoStatus = 0;            globalVariables.SendMessageInfo = 0;            byte[] data = getHttpImage(urlPath);            if (data == null) {                Log.i(TAG, "擷取到網頁頭像資源失敗");            } else {                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,                        data.length);                image.setImageBitmap(bitmap);                 Log.i(TAG, "擷取到網頁頭像資源");            }        } catch (Exception e) {            String error = "網路連接失敗,請重試!";            // Toast.makeText(MainActivity.this, error, 1).show();            Log.e(TAG, e.toString());        }    }/** httpGetImage根據路徑擷取圖片二進位編碼 */    public static byte[] getHttpImage(String path) throws Exception {        try {            URL url = new URL(path);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setRequestMethod("GET");            conn.setConnectTimeout(5 * 1000);            InputStream inStream = conn.getInputStream();            return readFromInput(inStream);        } catch (Exception e) {            Log.i(TAG, e.toString());            return null;        }    }
http擷取網狀圖片資源

https

擷取網路參數

public String getURL(String userName) {        String URLPath = "https://xxx&username="                + userName;        String result = "";        String str = "";        try {            URL url = new URL(URLPath);            SSLContext sslctxt = SSLContext.getInstance("TLS");            sslctxt.init(null, new TrustManager[] { new MyX509TrustManager() },                    new java.security.SecureRandom());            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();            conn.setSSLSocketFactory(sslctxt.getSocketFactory());            conn.setHostnameVerifier(new MyHostnameVerifier());            conn.connect();            int respCode = conn.getResponseCode();            Log.d(TAG, "ResponseCode=" + respCode);            if (respCode != 200) {                return "";            }            InputStream input = conn.getInputStream();            result = getInputString(input);            Log.d(TAG, "result:" + result);            input.close();            conn.disconnect();        } catch (Exception e) {            e.printStackTrace();        }        if (result != "") {            try {                JSONObject jsonObject = new JSONObject(result);                str = jsonObject.getString("url");            } catch (Exception e) {                Log.e(TAG, e.toString());            }        }        return str;    }
擷取json字串中的value
static class MyX509TrustManager implements X509TrustManager {        @Override        public void checkClientTrusted(X509Certificate[] chain, String authType)                throws CertificateException {            if (null != chain) {                for (int k = 0; k < chain.length; k++) {                    X509Certificate cer = chain[k];                    print(cer);                }            }            Log.d(TAG, "check client trusted. authType=" + authType);        }        @Override        public void checkServerTrusted(X509Certificate[] chain, String authType)                throws CertificateException {            if (null != chain) {                for (int k = 0; k < chain.length; k++) {                    X509Certificate cer = chain[k];                    print(cer);                }            }            Log.d(TAG, "check servlet trusted. authType=" + authType);        }        @Override        public X509Certificate[] getAcceptedIssuers() {            Log.d(TAG, "get acceptedissuer");            return null;        }        private void print(X509Certificate cer) {            int version = cer.getVersion();            String sinname = cer.getSigAlgName();            String type = cer.getType();            String algorname = cer.getPublicKey().getAlgorithm();            BigInteger serialnum = cer.getSerialNumber();            Principal principal = cer.getIssuerDN();            String principalname = principal.getName();            Log.d(TAG, "version=" + version + ", sinname=" + sinname                    + ", type=" + type + ", algorname=" + algorname                    + ", serialnum=" + serialnum + ", principalname="                    + principalname);        }    }    static class MyHostnameVerifier implements HostnameVerifier {        public boolean verify(String hostname, SSLSession session) {            Log.d(TAG,                    "hostname=" + hostname + ",PeerHost= "                            + session.getPeerHost());            return true;        }    }    private String getInputString(InputStream input) {        String content = "";        try {            InputStreamReader ir = new InputStreamReader(input);            BufferedReader br = new BufferedReader(ir);            StringBuilder sbuff = new StringBuilder();            while (null != br) {                String temp = br.readLine();                if (null == temp)                    break;                sbuff.append(temp).append(System.getProperty("line.separator"));            }            content = sbuff.toString();            // content=EncodingUtils.getString(baf.toByteArray(), "UTF-8");            content = URLDecoder.decode(content, "UTF-8");        } catch (Exception e) {            e.printStackTrace();        }        return content;    }
各種需要寫配合的方法類
Runnable runnableGetUserURL = new Runnable() {        @Override        public void run() {// 在新的線程中運行            if (globalVariables.UserName != "") {                imageURLString = getURL(UserName);                Log.d("MainActivity", "imageURL:" + imageURLString);                            }        }    };mThread = new Thread(runnableGetUserURL);mThread.start();
擷取參數的方法需要放入其他線程中

根據URL擷取圖片資源

public void setUserImage(String urlPath) {try {            Log.i(TAG, "https協議準備擷取網路頭像資源...");            Bitmap bitmap = httpsGetBitmap(urlPath);            image = (ImageView)findViewById(R.id.image);            image.setImageBitmap(bitmap);          } catch (Exception e) {            String error = "網路連接失敗,請重試!";            // Toast.makeText(MainActivity.this, error, 1).show();            Log.e(TAG, e.toString());        }    }private Bitmap httpsGetBitmap(String URLPath) throws Exception {        URL url = new URL(URLPath);        SSLContext sslctxt = SSLContext.getInstance("TLS");        sslctxt.init(null, new TrustManager[] { new MyX509TrustManager() },                new java.security.SecureRandom());        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();        conn.setSSLSocketFactory(sslctxt.getSocketFactory());        conn.setHostnameVerifier(new MyHostnameVerifier());        conn.connect();        InputStream inputSream = conn.getInputStream();        Bitmap bitmap = BitmapFactory.decodeStream(inputSream);        inputSream.close();        conn.disconnect();        return bitmap;    }
設定圖片資源

 

Android http https訪問網路及資源

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.