本篇內(nèi)容介紹了“java中HttpURLConnection的使用方法”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
牧野ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為成都創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:13518219792(備注:SSL證書合作)期待與您的合作!
代碼只需要jdk就行,不需要依賴第三方j(luò)ar包
package com.sean; import sun.net.www.protocol.http.HttpURLConnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; public class HttpURLConnectionTest { public static void main(String[] args) { sendRequestWithHttpURLConnection(); } private static void sendRequestWithHttpURLConnection() { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL("http://127.0.0.1:10000/service/sean?desc=description"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); //此時獲取的是字節(jié)流 InputStream in = connection.getInputStream(); //對獲取到的輸入流進(jìn)行讀取 reader = new BufferedReader(new InputStreamReader(in)); //將字節(jié)流轉(zhuǎn)化成字符流 StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine())!= null) { response.append(line); } System.out.println(response.toString()); } catch (Exception e ) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e ) { e.printStackTrace(); } } if ( connection!= null) { connection.disconnect(); } } } }).start(); } }
“java中HttpURLConnection的使用方法”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!