LoginUtil.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.sooka.sponest.middleground.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.commons.lang3.ObjectUtils;
  4. import org.apache.http.HttpEntity;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  9. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
  10. import org.apache.http.entity.ContentType;
  11. import org.apache.http.entity.StringEntity;
  12. import org.apache.http.impl.client.HttpClients;
  13. import org.apache.http.impl.client.LaxRedirectStrategy;
  14. import org.apache.http.ssl.SSLContextBuilder;
  15. import org.apache.http.util.EntityUtils;
  16. import javax.net.ssl.HostnameVerifier;
  17. import javax.net.ssl.SSLContext;
  18. public class LoginUtil {
  19. public static String login(String ip,String username, String psd) throws Exception {
  20. //取消证书认证
  21. SSLContext sslContext = SSLContextBuilder.create()
  22. .loadTrustMaterial(new TrustSelfSignedStrategy())
  23. .build();
  24. HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
  25. HttpClient httpClient = HttpClients.custom()
  26. .setSSLContext(sslContext)
  27. .setSSLHostnameVerifier(hostnameVerifier)
  28. .setRedirectStrategy(new LaxRedirectStrategy())
  29. .build();
  30. HttpPost httpPost = new HttpPost(ip + "/webapi?action=login");
  31. String password = MD5Util.Md5(psd);
  32. String requestBody = "{\r\n\t\"type\": \"USER\",\r\n\t\"from\": \"web\",\r\n\t\"username\": \"" + username +"\",\r\n\t\"password\": \"" + password + "\",\r\n\t\"browser\": \"Chrome/104.0.0.0\"\r\n}";
  33. StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
  34. httpPost.setEntity(requestEntity);
  35. HttpResponse response = httpClient.execute(httpPost);
  36. HttpEntity responseEntity = response.getEntity();
  37. String responseBody = EntityUtils.toString(responseEntity);
  38. JSONObject jsonObject = JSONObject.parseObject(responseBody);
  39. if (ObjectUtils.isNotEmpty(jsonObject) && jsonObject.get("status").toString().equals("0")) {
  40. return jsonObject.get("token").toString();
  41. } else {
  42. throw new Exception("获取token失败,请检查!!!");
  43. }
  44. }
  45. public static void main(String[] args) throws Exception {
  46. LoginUtil.login("https://www.gps51.com","演示测试组", "Ys2024");
  47. }
  48. }