HTTPS请求工具类汇总
HTTPS请求package com.sunzk.dreamsunlight.weixin.util;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import .ConnectException;import .URL;import .ssl.HttpsURLConnection; import .ssl.SSLContext;import .ssl.SSLSocketFactory; import .ssl.TrustManager;import net.sf.json.JSONException;import net.sf.json.JSONObject;import org.apache.log4j.Logger;importcom.sunzk.dreamsunlight.weixin.certificate.MyX509 TrustManager;import com.sunzk.dreamsunlight.weixin.model.Menu; importcom.sunzk.dreamsunlight.weixin.token.AccessToken;/**** @ClassName: WeiXinHttpsUtil*<p>* @Description: TODO(微信HTTPS请求工具类)*<p>* @author sunzk-dreamsunlight-QQ(1131341075)*<p>* @date 2016-11-14 上午10:05:56*<p>*/public class WeiXinHttpsUtil {private static Logger logger =Logger.getLogger(WeiXinHttpsUtil.class);// 获取access_token的接口地址(GET)限200(次/天)public final static String access_token_url = "https:///cgi-bin/token?grant_ty pe=client_credential&appid=APPID&secret=APPSECRET ";/*** 发起https请求并获取结果** @param requestUrl 请求地址* @param requestMethod 请求方式(GET、POST)* @param outputStr 提交的数据* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)*/public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {JSONObject jsonObject = null;StringBuffer buffer = new StringBuffer();try {// 创建SSLContext对象,并使用我们指定的信任管理器初始化TrustManager[] tm = { newMyX509TrustManager() };SSLContext sslContext =SSLContext.getInstance("SSL", "SunJSSE");sslContext.init(null, tm, newjava.security.SecureRandom());// 从上述SSLContext对象中得到SSLSocketFactory对象SSLSocketFactory ssf =sslContext.getSocketFactory();URL url = new URL(requestUrl);HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();httpUrlConn.setSSLSocketFactory(ssf);httpUrlConn.setDoOutput(true);httpUrlConn.setDoInput(true);httpUrlConn.setUseCaches(false);// 设置请求方式(GET/POST)httpUrlConn.setRequestMethod(requestMethod);if("GET".equalsIgnoreCase(requestMethod))httpUrlConn.connect();// 当有数据需要提交时if (null != outputStr) {OutputStream outputStream = httpUrlConn.getOutputStream();// 注意编码格式,防止中文乱码outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close();}// 将返回的输入流转换成字符串InputStream inputStream = httpUrlConn.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String str = null;while ((str =bufferedReader.readLine()) != null) {buffer.append(str);}bufferedReader.close();inputStreamReader.close();// 释放资源inputStream.close();inputStream = null;httpUrlConn.disconnect();jsonObject =JSONUtils.toJSONObject(buffer.toString());} catch (ConnectException ce) {("Weixin server connection timed out.");} catch (Exception e) {("https request error:{}", e);}return jsonObject;}/*** 获取access_token** @param appid 凭证* @param appsecret 密钥* @return*/public static AccessToken getAccessToken(String appid, String appsecret) {AccessToken accessToken = null;String requestUrl =access_token_url.replace("APPID",appid).replace("APPSECRET", appsecret);JSONObject jsonObject =httpRequest(requestUrl, "GET", null);// 如果请求成功if (null != jsonObject) {try {accessToken = new AccessToken();accessToken.setAccess_token(jsonObject.getString( "access_token"));accessToken.setExpires_in(jsonObject.getInt("expi res_in"));} catch (JSONException e) {("获取token失败 errcode:{} errmsg:{}"+jsonObject.getInt("errcode")+jsonObjec t.getString("errmsg"));accessToken = null;// 获取token失败 }}return accessToken;}public static void main(String[] args){String url ="https:///cgi-bin/material/batch get_material?access_token=vtKMZ09f7uuoB0s9Otn2g8Q IbCksRYRPJbKwBUB37wM0vhTQchYBC8gXV2OQjYmu8GcYhF1s dkpSzbu0dge6K_2qh5N6po3RMNpEA-A0WwgCQXgADAKYF"; String requestMethod = "GET";JSONObject obj =httpRequest(url,requestMethod,null);String info = JSONUtils.toJSONString(obj); System.out.println("<------返回信息------>"+info);}}HTTP请求package com.sunzk.dreamsunlight.weixin.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .URL;import .URLConnection;import .URLEncoder;import java.util.Map;/**** @ClassName: HttpUtil*<p>* @Description: TODO(HttpRequest请求工具类) *<p>* @author sunzk-dreamsunlight-QQ(1131341075) *<p>* @date 2016-11-11 上午10:44:44*<p>*/public class HttpUtil {/*** 使用Get方式获取数据** @param url* URL包括参数,http://HOST/XX?XX=XX&XXX=XXX* @param charset* @return*/public static String sendGet(String url, String charset) {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(), charset));String line;while ((line = in.readLine()) != null) { result += line;}} catch (Exception e) {System.out.println("发送GET请求出现异常!" + e);e.printStackTrace();}// 使用finally块来关闭输入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}/*** POST请求,字符串形式数据* @param url 请求地址* @param param 请求数据* @param charset 编码方式*/public static String sendPostUrl(String url, String param, String charset) {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(), charset));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;}/*** POST请求,Map形式数据* @param url 请求地址* @param param 请求数据* @param charset 编码方式*/public static String sendPost(String url, Map<String, String> param,String charset) {StringBuffer buffer = new StringBuffer(); if (param != null && !param.isEmpty()) { for (Map.Entry<String, String> entry : param.entrySet()) {buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(e ntry.getValue())).append("&");}}buffer.deleteCharAt(buffer.length() - 1);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(buffer);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));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;}public static void main(String[] args) {String url = "/";String encode = "GB2312";String content = sendGet(url,encode);System.out.println("<-------------HttpRquest 请求结果-------------->"+content);}}。
前端开发中常用的网络请求库和技术介绍
前端开发中常用的网络请求库和技术介绍随着互联网的快速发展,前端开发的重要性也日益凸显。
作为前端开发人员,我们经常需要与后端进行数据交互,这就需要使用网络请求库和技术来实现。
本文将介绍一些常用的网络请求库和技术,帮助前端开发人员更好地进行数据交互。
一、XMLHttpRequestXMLHttpRequest是前端开发中最常用的网络请求技术之一。
它是一种用于在浏览器和服务器之间发送HTTP请求的对象。
XMLHttpRequest可以实现异步请求,从而不会阻塞页面的加载。
通过使用XMLHttpRequest对象,我们可以发送GET、POST等请求,接收服务器返回的数据,并在页面上进行展示。
二、Fetch APIFetch API是一种新的网络请求技术,它提供了更简洁、更强大的接口来处理网络请求。
Fetch API使用Promise对象来处理异步请求,相比于XMLHttpRequest,代码更加简洁易读。
Fetch API支持跨域请求、请求取消等功能,可以更好地满足前端开发的需求。
三、AxiosAxios是一个基于Promise的HTTP客户端,用于浏览器和Node.js中发送HTTP请求。
它具有简洁的API和强大的功能,可以处理各种类型的请求,如GET、POST、PUT、DELETE等。
Axios还支持请求拦截器、响应拦截器等功能,可以对请求和响应进行全局的处理。
由于其易用性和可扩展性,Axios成为了前端开发中最受欢迎的网络请求库之一。
四、SuperagentSuperagent是一个轻量级的HTTP请求库,它支持浏览器和Node.js环境。
Superagent的API简洁易用,可以发送各种类型的请求,并处理服务器返回的数据。
它还提供了丰富的插件机制,可以根据需求进行扩展。
Superagent的灵活性和可定制性使其成为前端开发中常用的网络请求库之一。
五、jQuery AjaxjQuery是一个广泛使用的JavaScript库,其中的Ajax模块提供了简单易用的API来处理网络请求。
https请求的几种方式
https 请求的⼏种⽅式http/https 向服务端传递数据的⽅式,基本可以分为 5 种:url param、query、form-urlencoded、form-data、json。
get请求常⽤数据类型:要么是拼接在URl 后⾯, 要么就是 QueryString的⽅式传递,Content-Type 的值就不是那么重要了。
url paramRestful 的规范允许把参数写在 url 中,⽐如:这⾥的111就是路径中的参数 (url params)query通过 url 中 ?后⾯的⽤ & 分隔的字符串传递数据。
⽐如:Po st请求常⽤数据类型对于 POST 请求,Content-Type 的值就⾮常重要了application/x-www-form-urlencoded直接⽤from 表单提交数据就是这种, 他和query字符串的⽅式的区别是放在了body⾥,然后指定下 content-type是因为也是 query 字符串,所以也要⽤ encodeURIComponent 的 api 或者 QS的 库QS.stringify处理下。
其实这种设计也很容易理解,get 是把数据拼成 query 字符串放在 url 后⾯,于是设计表单的 post 提交⽅式的时候就直接⽤相同的⽅式把数据放在了 body ⾥。
通过 & 分隔的 form-urlencoded 的⽅式需要对内容做 url encode,如果传递⼤量的数据,⽐如上传⽂件的时候就不是很合适了,因为⽂件 encode ⼀遍的话太慢了,这时候就可以⽤ form-data。
form-data form-data 需要指定 content type 为 ,然后指定 boundary 也就是分割线。
对于⼆进制⽂件或者⾮ ASCII 字符的传输, 是低效的。
对于包含⽂件、⼆进制数据、⾮ ASCII 字符的内容,应该使⽤ 。
的请求体包含多个部分,需要通过 boundary 字符分割。
httpstaus汇总
httpstaus汇总常见HTTP状态码1.2.3.4.5.6.7.8.9.10.11.12.100 Continue初始的请求已经接受,客户应当继续发送请求的其余部分101 Switching Protocols服务器将遵从客户的请求转换到另外⼀种协议200 OK⼀切正常,对GET和POST请求的应答⽂档跟在后⾯201 Created服务器已经创建了⽂档,Location头给出了它的URL。
202 Accepted已经接受请求,但处理尚未完成。
203 Non-Authoritative Information⽂档已经正常地返回,但⼀些应答头可能不正确,因为使⽤的是⽂档的拷贝204 No Content没有新⽂档,浏览器应该继续显⽰原来的⽂档。
如果⽤户定期地刷新页⾯,⽽Servlet可以确定⽤户⽂档⾜够新,这个状态代码是很有⽤的205 Reset Content没有新的内容,但浏览器应该重置它所显⽰的内容。
⽤来强制浏览器清除表单输⼊内容206 Partial Content客户发送了⼀个带有Range头的GET请求,服务器完成了它300 Multiple Choices客户请求的⽂档可以在多个位置找到,这些位置已经在返回的⽂档内列出。
如果服务器要提出优先选择,则应该在Location应答头指明。
301 Moved Permanently客户请求的⽂档在其他地⽅,新的URL在Location头中给出,浏览器应该⾃动地访问新的URL。
302 Found类似于301,但新的URL应该被视为临时性的替代,⽽不是永久性的。
303 See Other类似于301/302,不同之处在于,如果原来的请求是POST,Location头指定的重定向⽬标⽂档应该通过GET提取304 Not Modified客户端有缓冲的⽂档并发出了⼀个条件性的请求(⼀般是提供If-Modified-Since头表⽰客户只想⽐指定⽇期更新的⽂档)。
列出常用的请求方法及用途
列出常用的请求方法及用途
在HTTP 协议中,常用的请求方法有以下几种:
1. GET:用于从服务器获取资源。
通常用于请求网页、图片、文件等。
请求时不会对服务器上的资源产生影响。
2. POST:用于向服务器提交数据,以创建或更新资源。
例如,提交表单数据、上传文件等。
请求可能会对服务器上的资源产生影响。
3. PUT:用于更新服务器上的资源。
通常用于更新现有资源的内容。
4. DELETE:用于删除服务器上的资源。
5. OPTIONS:用于获取服务器支持的请求方法或其他相关信息。
6. HEAD:与GET 方法类似,但只返回请求头部分,不返回请求体。
常用于检查资源的有效性或获取资源的元数据。
7. TRACE:用于追踪请求在服务器之间的传输路径。
主要用于调试和诊断。
8. PATCH:用于对服务器上的资源进行部分更新。
与PUT 方法类似,但只更新资源的一部分。
这些请求方法在Web 开发和应用程序中被广泛使用,每种方法都有其特定的用途和语义。
fastadmin curl请求方法
fastadmin curl请求方法作为一名职业写手,本文将为您详细介绍curl请求方法。
curl是一款功能强大的命令行HTTP请求工具,被广泛应用于各种开发场景。
接下来,我们将分析curl的语法结构,并列举一些常用的请求方式。
一、curl请求的基本语法curl请求的基本语法如下:```curl [options] -X HTTP_METHOD [URL]```其中,[options]为可选项,[URL]为请求的网址。
HTTP_METHOD为请求方法,如GET、POST等。
二、curl请求方法详解1.GET请求GET请求是用于获取指定资源的请求方法。
使用curl发送GET请求的示例代码如下:```curl -G https:///api/data```2.POST请求POST请求用于向服务器提交数据。
以下是使用curl发送POST请求的示例代码:```curl -d "key1=value1&key2=value2" -X POSThttps:///api/data```3.PUT请求PUT请求用于更新服务器上的资源。
以下是用curl发送PUT请求的示例代码:```curl -X PUT -H "Content-Type: application/json" -d "{"key": "new_value"}" https:///api/data```4.DELETE请求DELETE请求用于删除服务器上的资源。
以下是用curl发送DELETE请求的示例代码:```curl -X DELETE https:///api/data```5.PATCH请求PATCH请求用于对服务器上的资源进行部分更新。
以下是用curl发送PATCH请求的示例代码:```curl -X PATCH -H "Content-Type: application/json" -d "{"key":"new_value"}" https:///api/data```三、curl请求的实际应用场景1.网页爬虫:使用curl获取网页源代码,分析数据,实现自动化爬取。
get post 请求 工具
get post 请求工具如何使用GET和POST请求工具在互联网应用程序开发中,GET和POST请求是两种最常用的HTTP请求方法。
GET请求用于从服务器获取资源,而POST请求用于向服务器提交数据。
为了进行GET和POST请求,我们可以使用各种工具和技术。
本文将介绍几种使用GET和POST请求工具的方法,并通过一步一步的指导来解释如何使用这些工具。
第一部分:GET请求工具GET请求是一种用于从服务器获取资源的HTTP方法。
GET请求使用URL来传递数据,并且数据以键值对的形式附加在URL的查询字符串中。
以下是一些常见的GET请求工具,以及如何使用它们:1. Web浏览器:Web浏览器是最常见的GET请求工具之一。
打开任何现代Web浏览器,如Google Chrome、Mozilla Firefox或Microsoft Edge,在地址栏中输入目标URL并按下Enter键即可发送GET请求。
浏览器将向服务器发送GET请求,并在浏览器窗口中显示响应的结果。
你还可以在浏览器的网络调试工具中查看请求和响应的详细信息。
2. cURL:cURL是一个功能强大的用于在命令行界面中发送HTTP请求的工具。
你可以在任何支持cURL的操作系统上使用它。
要发送GET请求,只需在命令行中运行以下命令:curl [URL]替换[URL]为目标URL。
cURL将发送GET请求并显示服务器的响应。
你还可以使用各种选项来自定义请求,如添加HTTP头、设置超时时间等。
3. Postman:Postman是一个流行的API测试工具,支持发送各种类型的HTTP 请求,包括GET请求。
下载并安装Postman,然后打开它。
在Postman的地址栏中输入目标URL,选择GET请求方法,并点击“发送”按钮。
Postman将向服务器发送GET请求,并在结果窗口中显示响应。
第二部分:POST请求工具POST请求是一种用于向服务器提交数据的HTTP方法。
关于JAVA发送Https请求(HttpsURLConnection和HttpURLCon。。。
关于JAVA发送Https请求(HttpsURLConnection和HttpURLCon。
关于JAVA发送Https请求(HttpsURLConnection和HttpURLConnection)【转】https协议对于开发者⽽⾔其实只是多了⼀步证书验证的过程。
这个证书正常情况下被jdk/jre/security/cacerts所管理。
⾥⾯证书包含两种情况:1、机构所颁发的被认证的证书,这种证书的⽹站在浏览器访问时https头显⽰为绿⾊如百度2、个⼈所设定的证书,这种证书的⽹站在浏览器⾥https头显⽰为红⾊×,且需要点击信任该⽹站才能继续访问。
⽽点击信任这⼀步的操作就是我们在java代码访问https⽹站时区别于http请求需要做的事情。
所以JAVA发送Https请求有两种情况,三种解决办法:第⼀种情况:Https⽹站的证书为机构所颁发的被认证的证书,这种情况下和http请求⼀模⼀样,⽆需做任何改变,⽤HttpsURLConnection 或者HttpURLConnection都可以[java]1. public static void main(String[] args) throws Exception{2. URL serverUrl = new URL("https://xxxx");3. HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();4. conn.setRequestMethod("GET");5. conn.setRequestProperty("Content-type", "application/json");6. //必须设置false,否则会⾃动redirect到重定向后的地址7. conn.setInstanceFollowRedirects(false);8. conn.connect();9. String result = getReturn(conn);10. }11.12. /*请求url获取返回的内容*/13. public static String getReturn(HttpURLConnection connection) throws IOException{14. StringBuffer buffer = new StringBuffer();15. //将返回的输⼊流转换成字符串16. try(InputStream inputStream = connection.getInputStream();17. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, ConstantInfo.CHARSET);18. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);){19. String str = null;20. while ((str = bufferedReader.readLine()) != null) {21. buffer.append(str);22. }23. String result = buffer.toString();24. return result;25. }26. }第⼆种情况:个⼈所设定的证书,这种证书默认不被信任,需要我们⾃⼰选择信任,信任的办法有两种:A、将证书导⼊java的运⾏环境中从该⽹站下载或者从⽹站开发者出获取证书cacert.crt运⾏命令将证书导⼊java运⾏环境:keytool -import -keystore %JAVA_HOME%\jre\lib\security\cacerts -file cacert.crt -alias xxx 完成。
HttpUtil工具类,发送GetPost请求,支持Http和Https协议
HttpUtil⼯具类,发送GetPost请求,⽀持Http和Https协议HttpUtil⼯具类,发送Get/Post请求,⽀持Http和Https协议使⽤⽤Httpclient封装的HttpUtil⼯具类,发送Get/Post请求1. maven引⼊httpclient依赖<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.12</version></dependency>2. GET请求public static String doGet(String path, Map<String, String> param, Map<String, String> headers) {HttpGet httpGet = null;CloseableHttpResponse response = null;CloseableHttpClient httpClient = wrapClient(path);// 创建uriURIBuilder builder = null;try {builder = new URIBuilder(path);if (param != null) {for (String key : param.keySet()) {builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 创建http GET请求httpGet = new HttpGet(uri);if (headers != null && headers.size() > 0) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpGet.addHeader(entry.getKey(), entry.getValue());}}// 执⾏请求response = httpClient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {return EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {throw new RuntimeException("[发送Get请求错误:]" + e.getMessage());} finally {try {httpGet.releaseConnection();response.close();if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return null;}3. POST请求public static String doPostJson(String url, String jsonParam, Map<String, String> headers) {HttpPost httpPost = null;CloseableHttpResponse response = null;CloseableHttpClient httpClient = wrapClient(url);try {httpPost = new HttpPost(url);//addHeader,如果Header没有定义则添加,已定义则不变,setHeader会重新赋值httpPost.addHeader("Content-type","application/json;charset=utf-8");httpPost.setHeader("Accept", "application/json");StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);// entity.setContentType("text/json");// entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));httpPost.setEntity(entity);//是否有headerif (headers != null && headers.size() > 0) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 执⾏请求response = httpClient.execute(httpPost);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {return EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {throw new RuntimeException("[发送POST请求错误:]" + e.getMessage());} finally {try {httpPost.releaseConnection();response.close();if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return null;}3. 获取httpclient的⽅法这⾥会根据url⾃动匹配需要的是http的还是https的clientprivate static CloseableHttpClient wrapClient(String url) {CloseableHttpClient client = HttpClientBuilder.create().build();if (url.startsWith("https")) {client = getCloseableHttpsClients();}return client;}4. 对于https的需要⾃⼰实现⼀下clientprivate static CloseableHttpClient getCloseableHttpsClients() {// 采⽤绕过验证的⽅式处理https请求SSLContext sslcontext = createIgnoreVerifySSL();// 设置协议http和https对应的处理socket链接⼯⼚的对象Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager);// 创建⾃定义的httpsclient对象CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();return client;}private static SSLContext createIgnoreVerifySSL() {// 创建套接字对象SSLContext sslContext = null;try {//指定TLS版本sslContext = SSLContext.getInstance("TLSv1.2");} catch (NoSuchAlgorithmException e) {throw new RuntimeException("[创建套接字失败:] " + e.getMessage());}// 实现X509TrustManager接⼝,⽤于绕过验证X509TrustManager trustManager = new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,String paramString) throws CertificateException {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,String paramString) throws CertificateException {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}};try {//初始化sslContext对象sslContext.init(null, new TrustManager[]{trustManager}, null);} catch (KeyManagementException e) {throw new RuntimeException("[初始化套接字失败:] " + e.getMessage()); }return sslContext;}以上全部都测试通过,如果有错误,欢迎⼤佬们指出,感谢备注:完整版的让坚持成为品质,让优秀成为习惯!加油!。
HttpUtils发送http请求工具类(实例讲解)
HttpUtils发送http请求⼯具类(实例讲解)废话不多说,直接上代码import java.io.IOException;import java.io.UnsupportedEncodingException;import .URISyntaxException;import java.util.ArrayList;import java.util.Map;import mons.logging.Log;import mons.logging.LogFactory;import org.apache.http.HttpEntity;import ValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.client.utils.URIBuilder;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import com.pingan.qhcs.map.audit.constant.CodeConstant;import com.pingan.qhcs.map.audit.exception.MapException;public class HttpClientUtil {protected static Log logger = LogFactory.getLog(HttpClientUtil.class);private static PoolingHttpClientConnectionManager cm;private static String EMPTY_STR = "";private static String UTF_8 = "UTF-8";private static void init() {if (cm == null) {cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(50);// 整个连接池最⼤连接数cm.setDefaultMaxPerRoute(5);// 每路由最⼤连接数,默认值是2}}/*** 通过连接池获取HttpClient** @return*/public static CloseableHttpClient getHttpClient() {init();return HttpClients.custom().setConnectionManager(cm).build();}public static String httpGetRequest(String url) {HttpGet httpGet = new HttpGet(url);return getResult(httpGet);}public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {URIBuilder ub = new URIBuilder();ub.setPath(url);ArrayList<NameValuePair> pairs = covertParams2NVPS(params);ub.setParameters(pairs);HttpGet httpGet = new HttpGet(ub.build());return getResult(httpGet);}public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)throws URISyntaxException {URIBuilder ub = new URIBuilder();ub.setPath(url);ArrayList<NameValuePair> pairs = covertParams2NVPS(params);ub.setParameters(pairs);HttpGet httpGet = new HttpGet(ub.build());for (Map.Entry<String, Object> param : headers.entrySet()) {httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));}return getResult(httpGet);}public static String httpPostRequest(String url) {HttpPost httpPost = new HttpPost(url);return getResult(httpPost);}public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {HttpPost httpPost = new HttpPost(url);ArrayList<NameValuePair> pairs = covertParams2NVPS(params);httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));return getResult(httpPost);}public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)throws UnsupportedEncodingException {HttpPost httpPost = new HttpPost(url);for (Map.Entry<String, Object> param : headers.entrySet()) {httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));}ArrayList<NameValuePair> pairs = covertParams2NVPS(params);httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));return getResult(httpPost);}public static String httpPostRequest(String url, Map<String, Object> headers, String strBody)throws Exception {HttpPost httpPost = new HttpPost(url);for (Map.Entry<String, Object> param : headers.entrySet()) {httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));}httpPost.setEntity(new StringEntity(strBody, UTF_8));return getResult(httpPost);}private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();for (Map.Entry<String, Object> param : params.entrySet()) {pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));}return pairs;}/*** 处理Http请求** setConnectTimeout:设置连接超时时间,单位毫秒。
简述https请求流程
简述https请求流程下载温馨提示:该文档是我店铺精心编制而成,希望大家下载以后,能够帮助大家解决实际的问题。
文档下载后可定制随意修改,请根据实际需要进行相应的调整和使用,谢谢!并且,本店铺为大家提供各种各样类型的实用资料,如教育随笔、日记赏析、句子摘抄、古诗大全、经典美文、话题作文、工作总结、词语解析、文案摘录、其他资料等等,如想了解不同资料格式和写法,敬请关注!Download tips: This document is carefully compiled by theeditor. I hope that after you download them,they can help yousolve practical problems. The document can be customized andmodified after downloading,please adjust and use it according toactual needs, thank you!In addition, our shop provides you with various types ofpractical materials,such as educational essays, diaryappreciation,sentence excerpts,ancient poems,classic articles,topic composition,work summary,word parsing,copy excerpts,other materials and so on,want to know different data formats andwriting methods,please pay attention!1. 客户端发起请求:客户端(通常是浏览器)向服务器发送一个 https 请求。
