package com.sooka.sponest.middleground.util; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.ObjectUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; public class LoginUtil { public static String login(String ip,String username, String psd) throws Exception { //取消证书认证 SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(new TrustSelfSignedStrategy()) .build(); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; HttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(hostnameVerifier) .setRedirectStrategy(new LaxRedirectStrategy()) .build(); HttpPost httpPost = new HttpPost(ip + "/webapi?action=login"); String password = MD5Util.Md5(psd); 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}"; StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); JSONObject jsonObject = JSONObject.parseObject(responseBody); if (ObjectUtils.isNotEmpty(jsonObject) && jsonObject.get("status").toString().equals("0")) { return jsonObject.get("token").toString(); } else { throw new Exception("获取token失败,请检查!!!"); } } public static void main(String[] args) throws Exception { LoginUtil.login("https://www.gps51.com","演示测试组", "Ys2024"); } }