這篇文章將為大家詳細(xì)講解有關(guān)利用java實(shí)現(xiàn)發(fā)送http或get請(qǐng)求的方法有哪些,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:主機(jī)域名、虛擬主機(jī)、營(yíng)銷軟件、網(wǎng)站建設(shè)、安徽網(wǎng)站維護(hù)、網(wǎng)站推廣。
一、第一種方式,通過(guò)HttpClient方式,代碼如下:
public static String httpGet(String url, String charset) throws HttpException, IOException { String json = null; HttpGet httpGet = new HttpGet(); // 設(shè)置參數(shù) try { httpGet.setURI(new URI(url)); } catch (URISyntaxException e) { throw new HttpException("請(qǐng)求url格式錯(cuò)誤。"+e.getMessage()); } // 發(fā)送請(qǐng)求 HttpResponse httpResponse = client.execute(httpGet); // 獲取返回的數(shù)據(jù) HttpEntity entity = httpResponse.getEntity(); byte[] body = EntityUtils.toByteArray(entity); StatusLine sL = httpResponse.getStatusLine(); int statusCode = sL.getStatusCode(); if (statusCode == 200) { json = new String(body, charset); entity.consumeContent(); } else { throw new HttpException("statusCode="+statusCode); } return json; }
二、第二種方式,通過(guò)流的形式,貼代碼:
/** * 發(fā)送http get請(qǐng)求 * * @param getUrl * @return */ public String sendGetRequest(String getUrl) { StringBuffer sb = new StringBuffer(); InputStreamReader isr = null; BufferedReader br = null; try { URL url = new URL(getUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setAllowUserInteraction(false); isr = new InputStreamReader(url.openStream()); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { fileOperator.closeResources(isr, br); } return sb.toString(); } }
關(guān)于利用java實(shí)現(xiàn)發(fā)送http或get請(qǐng)求的方法有哪些就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
分享名稱:利用java實(shí)現(xiàn)發(fā)送http或get請(qǐng)求的方法有哪些
網(wǎng)站網(wǎng)址:http://www.rwnh.cn/article42/ggohhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、營(yíng)銷型網(wǎng)站建設(shè)、電子商務(wù)、建站公司、域名注冊(cè)、搜索引擎優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)