您的位置:首页 > 理论基础 > 计算机网络

通过HttpURLConnection连接服务器,发送报文,获取服务器报文返回

2017-11-29 10:23 591 查看
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.di
99ab
sconnect();
}
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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: