接口使用Http发送post请求工具类
HttpClientKit
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP; import com.alibaba.fastjson.JSONObject; /**
* @ClassName HttpClientKit.java
* @Description TODO
*
* @author D.C
* @version V1.0
* @CreateDate 2018年1月3日 下午8:21:49
*
*/
public class HttpClientKit { public static String post(String url, net.sf.json.JSONObject json) { CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = ""; try { StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s); // 发送请求
HttpResponse httpResponse = client.execute(post); // 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close(); result = strber.toString();
System.out.println(result); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
finally {
//client.
}
return result;
} public static String postMsg(String url, JSONObject json) { CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/json");
//post.addHeader("Authorization", "Basic YWRtaW46");
post.addHeader("ApiKey", "hswl");
post.addHeader("PostMethod", "POST");
String result = ""; try { StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s); // 发送请求
HttpResponse httpResponse = client.execute(post); // 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close(); result = strber.toString();
System.out.println(result); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
finally {
//client.
}
return result;
}
}
HttpKit
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; /**
* @ClassName HttpKit.java
* @Description TODO
*/
public class HttpKit { private static final String DEFAULT_CHARSET = "UTF-8"; /**
* 发送Get请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = new StringBuffer();
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(50000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(50000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect(); InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
//bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
} catch (Exception e) {
}
return bufferRes.toString();
} /**
* 发送Get请求
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
if(https != null && https){
return get(url);
}else{
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect(); InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
}
} /**
* 发送Get请求
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String get(String url, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
return get(initParams(url, params));
} /**
* 发送Post请求
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
System.out.println("url:"+url+" params: "+params);
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 连接超时
http.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(25000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
http.connect(); OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close(); InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 关闭连接
http.disconnect();
}
return bufferRes.toString();
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
} /**
* 上传媒体文件
* @param url
* @param params
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
public static String upload(String url,File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // 定义数据分隔线
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream fs = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = fs.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个
fs.close();
out.write(end_data);
out.flush();
out.close(); // 定义BufferedReader输入流来读取URL的响应
InputStream in = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (conn != null) {
// 关闭连接
conn.disconnect();
}
return bufferRes.toString();
} /**
* 下载资源
* @param url
* @return
* @throws IOException
*/ /**
*
* @param url
* @param params
* @return
*/
private static String initParams(String url, Map<String, String> params){
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
} else {
sb.append("&");
}
boolean first = true;
for (Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
sb.append("&");
}
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append("=");
if (value != null && !value.equals("")) {
try {
sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return sb.toString();
} public static void main(String[] args) throws Exception{
String result = get("http://localhost:8080/hstms/AjaxWebApiTester?param1=hello¶m2=java¶m3=world", false);
System.out.println(result);
}
} /**
* 证书管理
*/
class MyX509TrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() {
return null;
} @Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
测试方法、
Map<String, Object> map = new HashMap<String, Object>();
map.put("oid", jsonObject.get("oid"));
map.put("soid", jsonObject.get("soid"));
map.put("code", jsonObject.get("code"));
map.put("name", jsonObject.get("name"));
System.out.println("任务启动jsonObject"+jsonObject.toString()); net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(map); String result=HttpClientKit.post(POST_URL,json); return result;
接口使用Http发送post请求工具类的更多相关文章
- Java 发送 Https 请求工具类 (兼容http)
依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...
- Java 发送 Http请求工具类
HttpClient.java package util; import java.io.BufferedReader; import java.io.IOException; import java ...
- HttpUtils 发送http请求工具类
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxEx ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
- 【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...
随机推荐
- 低门槛彻底理解JavaScript中的深拷贝和浅拷贝
作者 | 吴胜斌 来源 | https://www.simbawu.com/article/search/9 在说深拷贝与浅拷贝前,我们先看两个简单的案例: //案例1var num1 = 1, nu ...
- anaconda3创建py2环境
查看conda的py环境conda info -e # 创建一个名为python34的环境,指定Python版本是3.4(创建py27操作一样)conda create -n py34 python= ...
- python 常用技巧 — 字典 (dictionary)
目录: 1. python 相加字典所有的键值 (python sum all values in dictionary) 2. python 两个列表分别组成字典的键和值 (python two l ...
- 百度语音 python
python实现语音识别 我们用到是百度语音识别,因为不掏钱哈哈!首先去百度官网去创建你的 APPID AK SK 这个网上很多大家没创建的自己看下 目前本SDK的功能同REST API,需要联网调用 ...
- 【leetcode】640. Solve the Equation
题目如下: 解题思路:本题的思路就是解析字符串,然后是小学时候学的解方程的思想,以"2x+3x-6x+1=x+2",先把左右两边的x项和非x项进行合并,得到"-x+1=x ...
- CPU的历史
https://zhuanlan.zhihu.com/p/64537796 很多人都对电脑硬件有一点的了解,本人也算略懂一二,所以今天来为大家说说电脑的主要硬件之一––CPU(中央处理器). 那么我们 ...
- mysql5.6和5.7安装 centos
mysql5.7安装 tar xf mysql--linux-glibc2.-x86_64.tar.gz mv mysql--linux-glibc2.-x86_64 /opt/mysql yum i ...
- getjob
[op@TIM getpage]$ cat job.py #coding: utf- #title..href... import urllib.request import time url=[ p ...
- 机器学习之KNN---k最近邻算法-机器学习
KNN算法是机器学习中入门级算法,属于监督性学习算法.SupervisedLearning. 通过Plinko游戏来介绍该算法. 就是随机在上面投球,然后球进下面的哪个地方就得多少分. 然后在规定得投 ...
- 改进持续交付中的CI环节
改进持续交付中的CI环节 在当前 DevOps 的趋势下,持续集成(CI)和持续部署(CD)具有支柱性地位,那么能够成功搭建 CI/CD 流水线就至关重要了. 今天我就讲一讲如何做好CI部分,让我们的 ...