溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

利用java實現(xiàn)發(fā)送http或get請求的方法有哪些

發(fā)布時間:2020-11-20 16:22:25 來源:億速云 閱讀:231 作者:Leah 欄目:編程語言

這篇文章將為大家詳細講解有關(guān)利用java實現(xiàn)發(fā)送http或get請求的方法有哪些,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

一、第一種方式,通過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("請求url格式錯誤。"+e.getMessage());
  }
  // 發(fā)送請求
  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;
}

二、第二種方式,通過流的形式,貼代碼:

/**
  * 發(fā)送http get請求
  * 
  * @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實現(xiàn)發(fā)送http或get請求的方法有哪些就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI