Http請求 post get

來源:互聯網
上載者:User

標籤:

package com.sprucetec.tms.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* HttpInvoker.
*
* @author Yinqiang Du
* @date 2016/8/11
*/
public class HttpInvokerUtils {
/**
* 日誌.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(HttpInvokerUtils.class);

/**
* 發起http get 請求擷取返回結果.
*
* @param getURL 請求路徑 .
* @return
* @throws Exception
*/
public static void readContentFromGet(String getURL) throws IOException {
// 拼湊get請求的URL字串,使用URLEncoder.encode對特殊和不可見字元進行編碼
URL getUrl = new URL(getURL);
// 根據拼湊的URL,開啟串連,URL.openConnection函數會根據 URL的類型,
// 返回不同的URLConnection子類的對象,這裡URL是一個http,因此實際返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
// 進行串連,但是實際上get request要在下一句的 connection.getInputStream()函數中才會真正發到
// 伺服器
connection.connect();
// 取得輸入資料流,並使用Reader讀取
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println(" ============================= ");
System.out.println(" Contents of get request ");
System.out.println(" ============================= ");
String lines;
while ((lines = reader.readLine()) != null) {
System.out.println(lines);
}
reader.close();
// 中斷連線
connection.disconnect();
System.out.println(" ============================= ");
System.out.println(" Contents of get request ends ");
System.out.println(" ============================= ");
}

/**
* 發起http post 請求擷取返回結果.
*
* @param urlStr 請求路徑 .
* @param requestParamsJson json字串.
* @return
* @throws Exception
*/
public static void sendRequest(String urlStr, String requestParamsJson) throws Exception {
BufferedOutputStream bufOutPut = null;
BufferedReader bufferedReader = null;
HttpURLConnection httpConn = null;
try {
URL url = new URL(urlStr);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoInput(true); // 設定是否從httpUrlConnection讀入,預設情況下是true;
httpConn.setDoOutput(true); // 設定是否向httpUrlConnection輸出,因為這個是post請求,參數要放在http本文內,因此需要設為true, 預設情況下是false;
httpConn.setRequestMethod("POST");// 設定請求的方法為"POST",預設是GET
httpConn.setAllowUserInteraction(false); //是否允許使用者互動
httpConn.setUseCaches(false); // Post 請求不能使用緩衝
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Accept-Charset", "UTF-8");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長串連
httpConn.setRequestProperty("Content-Type", "application/json"); // 設定傳送的內容類型是可序列化的java對象
// 此處getOutputStream會隱含的進行connect(即:如同調用上面的connect()方法,
bufOutPut = new BufferedOutputStream(httpConn.getOutputStream());
httpConn.connect();
byte[] bdat = requestParamsJson.getBytes("UTF-8");// 解決中文亂碼問題
bufOutPut.write(bdat, 0, bdat.length);
bufOutPut.flush();

// 根據ResponseCode判斷串連是否成功
int responseCode = httpConn.getResponseCode();
if (responseCode != 200) {
LOGGER.error(" Error===" + responseCode);
} else {
LOGGER.info("Post Success!");
}
// 定義BufferedReader輸入資料流來讀取URL的ResponseData
bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
LOGGER.error("send post request error!" + e);
} finally {
httpConn.disconnect(); // 中斷連線
try {
if (bufOutPut != null) {
bufOutPut.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Http請求 post get

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.