Java发送HTTPS请求

拼搏现实的明天。 2022-03-02 02:39 551阅读 0赞

前言

上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 。我也是由于对接了其他企业后总结了一套发送 https的工具。大家网上找方法很多的,但是可不是你粘过来就能用啊,我也是踩过坑的,所以我这个工具,只要粘贴到你们自己项目里就可以用。我的工具跟网上没什么区别,唯一的区别是我亲身实战过,把需要注意的细节列出来,不让大家浪费时间。

正文

本文只介绍 发送 post 请求,既然选择了 https 就不会用get,因为get也是不安全的。

读前须知

我会把需要依赖的包和引入的包先贴给大家,防止大家引用错误。

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpcore</artifactId>
  4. <version>4.4.8</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.httpcomponents</groupId>
  8. <artifactId>httpclient</artifactId>
  9. <version>4.5.3</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.testng</groupId>
  13. <artifactId>testng</artifactId>
  14. <version>6.11</version>
  15. <scope>test</scope>
  16. </dependency>
  17. import org.apache.http.conn.ClientConnectionManager;
  18. import org.apache.http.conn.scheme.Scheme;
  19. import org.apache.http.conn.scheme.SchemeRegistry;
  20. import org.apache.http.conn.ssl.SSLSocketFactory;
  21. import org.apache.http.impl.client.DefaultHttpClient;
  22. import javax.net.ssl.SSLContext;
  23. import javax.net.ssl.TrustManager;
  24. import javax.net.ssl.X509TrustManager;
  25. import java.security.cert.CertificateException;
  26. import java.security.cert.X509Certificate;
  27. <----工具类---->
  28. import org.apache.http.HttpEntity;
  29. import org.apache.http.HttpResponse;
  30. import org.apache.http.HttpStatus;
  31. import org.apache.http.NameValuePair;
  32. import org.apache.http.client.entity.UrlEncodedFormEntity;
  33. import org.apache.http.client.methods.HttpPost;
  34. import org.apache.http.entity.StringEntity;
  35. import org.apache.http.impl.client.DefaultHttpClient;
  36. import org.apache.http.message.BasicNameValuePair;
  37. import org.apache.http.util.EntityUtils;
  38. import org.slf4j.Logger;
  39. import org.slf4j.LoggerFactory;
  40. import java.util.ArrayList;
  41. import java.util.Iterator;
  42. import java.util.List;
  43. import java.util.Map;

HTTPS 发送 POST 请求

一共需要两个类,不要问为什么,复制过去就能用,不能用你找我,下面有微信。

  1. public class SSLClient extends DefaultHttpClient {
  2. public SSLClient() throws Exception {
  3. super();
  4. //传输协议需要根据自己的判断
  5. SSLContext ctx = SSLContext.getInstance("TLS");
  6. X509TrustManager tm = new X509TrustManager() {
  7. @Override
  8. public void checkClientTrusted(X509Certificate[] chain,
  9. String authType) throws CertificateException {
  10. }
  11. @Override
  12. public void checkServerTrusted(X509Certificate[] chain,
  13. String authType) throws CertificateException {
  14. }
  15. @Override
  16. public X509Certificate[] getAcceptedIssuers() {
  17. return null;
  18. }
  19. };
  20. ctx.init(null, new TrustManager[]{tm}, null);
  21. SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  22. ClientConnectionManager ccm = this.getConnectionManager();
  23. SchemeRegistry sr = ccm.getSchemeRegistry();
  24. sr.register(new Scheme("https", 443, ssf));
  25. }
  26. }

这里发送 https 的操作有两个,一个是传 json ,一个是传 map ,大家根据自己需要自行复制使用

第一种是传 json 作为参数

参数说明:

url:url

map:json参数

charset:写死 utf-8

  1. public String doPost(String url, String map, String charset) {
  2. org.apache.http.client.HttpClient httpClient = null;
  3. HttpPost httpPost = null;
  4. String result = null;
  5. try {
  6. httpClient = new SSLClient();
  7. httpPost = new HttpPost(url);
  8. //设置参数
  9. httpPost.addHeader("Accept", "application/json");
  10. httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
  11. StringEntity stringEntity = new StringEntity(map);
  12. stringEntity.setContentEncoding("UTF-8");
  13. stringEntity.setContentType("application/json");
  14. httpPost.setEntity(stringEntity);
  15. HttpResponse response = httpClient.execute(httpPost);
  16. if (response != null) {
  17. HttpEntity resEntity = response.getEntity();
  18. if (resEntity != null) {
  19. result = EntityUtils.toString(resEntity, charset);
  20. }
  21. }
  22. } catch (Exception ex) {
  23. ex.printStackTrace();
  24. }
  25. return result;
  26. }

测试类,送大家一个MD5加密,其实我就懒得删掉了。

  1. private String url = "https://www.xxxxxxxx.com/openapi/page/gettoken";
  2. private String charset = "utf-8";
  3. private HttpClient httpClientUtil = new HttpClient();
  4. @Test
  5. public void HttpsPostTest() throws Exception {
  6. String ver = "1.0";
  7. String msgId = "91b024e3-06ca-4a79-9993-1472d0fdb973";
  8. String appId = "300011853779";
  9. String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
  10. String appKey = "A0702827F21C9CC7DDC93AEF24B6B16B";
  11. String sign = md5(ver + appId + msgId + timestamp + appKey).toUpperCase();
  12. result.put("ver", ver);
  13. result.put("msgId", msgId);
  14. result.put("appId", appId);
  15. result.put("timestamp", timestamp);
  16. result.put("openType", "1");
  17. result.put("message", "");
  18. result.put("abilityId", "");
  19. result.put("expandParams", "");
  20. result.put("signType", "1");
  21. result.put("sign", sign);
  22. String encryptStr = result.toString();
  23. System.out.println("encryptStr:" + encryptStr);
  24. String httpOrgCreateTestRtn = httpClientUtil.doPost(url, encryptStr, charset);
  25. System.out.println("result:" + httpOrgCreateTestRtn);
  26. }
  27. public static String md5(String text) {
  28. String result="";
  29. try {
  30. MessageDigest md = MessageDigest.getInstance("MD5");
  31. md.update(text.getBytes("UTF-8"));
  32. byte b[] = md.digest();
  33. int i;
  34. StringBuffer buf = new StringBuffer("");
  35. for (int offset = 0; offset < b.length; offset++) {
  36. i = b[offset];
  37. if (i < 0)
  38. i += 256;
  39. if (i < 16)
  40. buf.append("0");
  41. buf.append(Integer.toHexString(i));
  42. }
  43. result = buf.toString();
  44. // System.out.println("result: " + buf.toString());// 32位的加密
  45. // System.out.println("result: " + buf.toString().substring(8, 24));// 16位的加密
  46. } catch (NoSuchAlgorithmException e) {
  47. // TODO Auto-generated catch block
  48. } catch (UnsupportedEncodingException e) {
  49. // TODO Auto-generated catch block
  50. }
  51. return result;
  52. }

第二种传map作为参数

  1. public String doPost(String url, Map<String,String> map, String charset) {
  2. org.apache.http.client.HttpClient httpClient = null;
  3. HttpPost httpPost = null;
  4. String result = null;
  5. try {
  6. httpClient = new SSLClient();
  7. httpPost = new HttpPost(url);
  8. //设置参数
  9. List<NameValuePair> list = new ArrayList<NameValuePair>();
  10. Iterator iterator = map.entrySet().iterator();
  11. while (iterator.hasNext()) {
  12. Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
  13. list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
  14. }
  15. if (list.size() > 0) {
  16. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
  17. entity.setContentType("application/json");
  18. httpPost.setHeader("Accept", "application/json");
  19. httpPost.setHeader("Content-type", "application/json;charset=utf-8");
  20. httpPost.setEntity(entity);
  21. }
  22. HttpResponse response = httpClient.execute(httpPost);
  23. if (response != null) {
  24. HttpEntity resEntity = response.getEntity();
  25. if (resEntity != null) {
  26. result = EntityUtils.toString(resEntity, charset);
  27. }
  28. }
  29. } catch (Exception ex) {
  30. ex.printStackTrace();
  31. }
  32. return result;
  33. }

发送的时候 大家把上面 json 测试的demo 中 JSONObject 改成Map 就可以。

如有疑问

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODAwMzM4OQ_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,551人围观)

还没有评论,来说两句吧...

相关阅读