HttpUtil 发送请求
作者:互联网
/**
* 发送http请求 get方式
*
* @param url
* @return
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 发送http请求 post方式
* @param reqParams
* @return
* @throws Exception
*/
public static String sendPost(String url, Map<String, String> reqParams) throws Exception {
String response = "";
URL serverUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
//设置请求编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=----footfoodapplicationrequestnetwork");
conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Range", "bytes=" + "");
//创建请求参数
StringBuilder sb = new StringBuilder();
if (reqParams != null) {
for (Map.Entry<String, String> entry : reqParams.entrySet()) {
sb.append("------footfoodapplicationrequestnetwork\r\n");
sb.append("Content-Disposition: form-data; name=\"");
sb.append(entry.getKey());
sb.append("\"\r\n\r\n");
sb.append(entry.getValue());
sb.append("\r\n");
}
sb.append("------footfoodapplicationrequestnetwork--\r\n");
}
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
out.write(sb.toString());
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is, "utf-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
response = buffer.toString();
conn.disconnect();
return response;
}
/**
*
* @param url https://hrit.haier.net:8899/ashx/rili.ashx
* @param param "?empnumber=" + empnumber +"&ty="+ ty +"&tm="+tm
* @return
*/
public static String sendGet(String url,String param) {
String result = "";
try {
String urlName = url + param;
URL U = new URL(urlName);
URLConnection connection = U.openConnection();
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
} catch (Exception e) {
throw new RuntimeException("创建连接失败" + e);
}
return result;
}
/**
* 发送http请求 post方式
* 发送内容格式 json字符串
*
* @param url
* @param reqParams
* @return
* @throws Exception
*/
public static String sendPostStr(String url, Map<String, String> reqParams) throws Exception {
String response = "";
URL serverUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
//设置请求编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=----footfoodapplicationrequestnetwork");
conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Range", "bytes=" + "");
//创建请求参数
StringBuilder sb = new StringBuilder();
if (reqParams != null) {
JSONObject jsonObject = JSONObject.fromObject(reqParams);
sb.append("------footfoodapplicationrequestnetwork\r\n");
sb.append("Content-Disposition: form-data; name=\"");
sb.append("resultMap");
sb.append("\"\r\n\r\n");
sb.append(jsonObject.toString());
sb.append("\r\n");
sb.append("------footfoodapplicationrequestnetwork--\r\n");
}
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
out.write(sb.toString());
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is, "utf-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
response = buffer.toString();
conn.disconnect();
return response;
}
/**
* 发送request请求,以流的形式发送,无参发送
* @param url
* @param str
* @return
* @throws Exception
*/
public static String httpRequest(String url,String str) throws Exception{
BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build(),
null,
null,
null
);
HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
HttpPost httpPost = new HttpPost(url);
StringEntity postEntity = new StringEntity(str, "UTF-8");
httpPost.addHeader("Content-Type", "text/plain");
httpPost.setEntity(postEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
}
//******************************************** 自定义head
public static String get(String url, Map<String, String> headMap) throws Exception {
HttpGet httpGet = new HttpGet(url);
if (headMap != null) {
for (String key : headMap.keySet()) {
httpGet.addHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
}
public static InputStream down(String url, Map<String, String> headMap) throws Exception {
url = url.replaceAll("\\\\", "/");
HttpGet httpGet = new HttpGet(url);
if (headMap != null) {
for (String key : headMap.keySet()) {
httpGet.setHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream input = entity.getContent();
return input;
}
public static String post(String url, Map<String, String> headMap) throws Exception {
HttpPost httpPost = new HttpPost(url);
if (headMap != null) {
for (String key : headMap.keySet()) {
httpPost.setHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
}
public static String post(String url, List<NameValuePair> params, Map<String, String> headMap) throws Exception {
HttpPost httpPost = new HttpPost(url);
// 添加参数
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
if (headMap != null) {
for (String key : headMap.keySet()) {
httpPost.setHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
}
public static String postWithTimeout(String url, List<NameValuePair> params, Map<String, String> headMap) throws Exception {
HttpPost httpPost = new HttpPost(url);
// 添加参数
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
if (headMap != null) {
for (String key : headMap.keySet()) {
httpPost.setHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).build();
httpPost.setConfig(requestConfig);
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
}
public static String post(String url, String entityString, Map<String, String> headMap) throws Exception {
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(entityString, Charset.forName("UTF-8"));
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("utf-8");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
if (headMap != null) {
for (String key : headMap.keySet()) {
httpPost.setHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
}
/*POST请求方式传form-data类型的数据*/
public static String doPost(String url, HashMap<String, String> map, String authorization) throws Exception {
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("Authorization", authorization);
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("创建连接失败" + e);
} catch (IOException e) {
throw new RuntimeException("创建连接失败" + e);
}
return result;
}
/*POST请求方式传form-data类型的数据*/
public static String doPostFormData(String url, Map<String, String> map, Map<String, String> header) throws Exception {
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("appId", header.get("appId"));
httpPost.setHeader("appKey", header.get("appKey"));
httpPost.setHeader("sign", header.get("sign"));
httpPost.setHeader("timestamp", header.get("timestamp"));
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("创建连接失败" + e);
} catch (IOException e) {
throw new RuntimeException("创建连接失败" + e);
}
return result;
}
public static String sendGet(String url,String param) {
String result = "";
try {
String urlName = url + param;
URL U = new URL(urlName);
URLConnection connection = U.openConnection();
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
} catch (Exception e) {
throw new RuntimeException("创建连接失败" + e);
}
return result;
}
public static String delete(String url, Map<String, String> headMap) throws Exception {
HttpDelete httpDelete = new HttpDelete(url);
if (headMap != null) {
for (String key : headMap.keySet()) {
httpDelete.setHeader(key, headMap.get(key));
}
}
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpDelete);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
}
/**
* 将流 保存为数据数组
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 创建一个Buffer字符串
byte[] buffer = new byte[1024];
// 每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
// 使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
// 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
// 关闭输入流
inStream.close();
// 把outStream里的数据写入内存
return outStream.toByteArray();
}
public static String doPost(String url, Map<String, String> header, Map<String, Object> body) throws Exception {
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Iterator<Map.Entry<String, String>> headerIt = header.entrySet().iterator();
while (headerIt.hasNext()) {
Map.Entry<String, String> entry = headerIt.next();
httpPost.setHeader(entry.getKey(), entry.getValue().toString());
}
Iterator<Map.Entry<String, Object>> it = body.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue() == null? "" : entry.getValue().toString());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("创建连接失败" + e);
} catch (IOException e) {
throw new RuntimeException("创建连接失败" + e);
}
return result;
}
public static String postFormData(String url, Map<String, String> header, Map<String, Object> params) {
HttpPost httpPost = new HttpPost(url);
if(header != null) {
for (String key : header.keySet()) {
httpPost.setHeader(key, header.get(key));
}
}
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if(params != null) {
for (String key : params.keySet()) {
formparams.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String resBody = EntityUtils.toString(entity, "UTF-8");
return resBody;
} catch (Exception e) {
e.printStackTrace();
throw new BizBaseException(BizExceptionCode.REQUEST_OTHER_APP_ERROR);
}
}
标签:请求,url,发送,httpPost,new,null,HttpUtil,response,String 来源: https://www.cnblogs.com/ysySelf/p/14128577.html