1. 程式人生 > >通過HttpURLConnection連線伺服器,傳送報文,獲取伺服器報文返回

通過HttpURLConnection連線伺服器,傳送報文,獲取伺服器報文返回

Java 通過HttpURLConnection連線伺服器 傳送 POST 和 GET 請求

package com.dataservice.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import javax.net.ssl.HttpsURLConnection;

import
lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * 通過HttpURLConnection連線伺服器,傳送報文,獲取伺服器報文返回 * * @author
xiaoding * */
@Slf4j public class SendMess { /** * * @param content * request content * @param charset * @param postUrl * post URL * @return massage from remote server */ public static String transferData(String content, Charset charset, String postUrl, String conentType) throws
IOException { HttpURLConnection connection = null; BufferedReader reader = null; StringBuilder sb = new StringBuilder(); try { byte[] postData = content.getBytes(charset); int postDataLength = postData.length; // 配置連線 URL url = new URL(postUrl); connection = (HttpURLConnection) url.openConnection(); if (connection instanceof HttpsURLConnection) { SslContextUtils.createInstance().initHttpsConnect((HttpsURLConnection) connection); } // connection.setRequestProperty("Content-type", ); connection.setConnectTimeout(5000); connection.setReadTimeout(20000); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", conentType); connection.setRequestProperty("charset", charset.displayName()); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setUseCaches(false); // 傳送請求 connection.getOutputStream().write(postData); connection.getOutputStream().flush(); connection.getOutputStream().close(); // 讀取響應 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset)); char[] buf = new char[1024]; int length = 0; while ((length = reader.read(buf)) > 0) { sb.append(buf, 0, length); } } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { IOUtils.closeQuietly(reader); } } String res = sb.toString(); return res; } public static String sendDataByGet(String url, String params) throws IOException { // Create HttpClient Object CloseableHttpClient client = HttpClients.createDefault(); StringBuilder urlString = new StringBuilder(); urlString.append(url); urlString.append("?"); urlString.append(params); String urlReq = urlString.toString(); log.debug("request url is {}", urlReq); // 建立Get方法例項 HttpGet httpsgets = new HttpGet(urlReq); String strRep = ""; try { HttpResponse response = client.execute(httpsgets); HttpEntity entity = response.getEntity(); if (entity != null) { strRep = EntityUtils.toString(response.getEntity()); httpsgets.abort(); } } catch (IOException e) { log.error("http request error", e); throw e; } return strRep; } }

呼叫示例:

String param = "companyCode=" + companyCode + "&productCode=" + productCode + "&str=" + paramJson + "&secretType=" + secretType + "&signType" + signType + "&sign=" + sign";

String resp = SendMess.sendDataByGet(url, param);

String res =  SendMess.transferData(param, DsContent.DATA_CHARSET, url, "application/x-www-form-urlencoded;charset=utf-8");