java - 无法使用 Java 发送 Post 请求
问题描述
我正在尝试根据以下代码发出发布请求:
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Map<String, String> map = new HashMap<String, String>();
map.put("emailadress", "");
map.put("emailSubject", "Pendência para lançamento de horas do Jira");
map.put("emailBody", "Se você visualizar esta mensagem o bot funcionou");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Accept",MediaType.ALL_VALUE);
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<>(map,requestHeaders);
String url = new StringBuilder().append("...").toString();
restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class);
logger.info("Bot enviado com sucesso!");
} catch (RestClientException e) {
logger.error("Erro ao enviar Bot.", e);
throw e;
}
在 Postman,这个请求可以正常工作并且不需要身份验证,它无需登录名、密码或令牌即可工作。但是,上面的代码不起作用。
日志控制台的一部分如下:
lientExec - Executing request POST /workflows/fbf4c29cbcad4679b1a1159fff7b07f9/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%252Ftriggers%252Fmanual%252Frun&sv=1.0&sig=zxm46aQnBj3ZTKPOddnnwUgtQZoQcQfixNtXVxAJjPg HTTP/1.1
00:11:45.884 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Target auth state: UNCHALLENGED
00:11:45.888 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Proxy auth state: UNCHALLENGED
00:11:45.896 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> POST /workflows/fbf4c29cbcad4679b1a1159fff7b07f9/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%252Ftriggers%252Fmanual%252Frun&sv=1.0&sig=zxm46aQnBj3ZTKPOddnnwUgtQZoQcQfixNtXVxAJjPg HTTP/1.1
00:11:45.896 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept: */*
00:11:45.896 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Type: application/json
00:11:45.896 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Content-Length: 168
00:11:45.897 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Host: prod-12.westeurope.logic.azure.com:443
00:11:45.897 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Connection: Keep-Alive
00:11:45.897 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.10 (Java/1.8.0_261)
00:11:45.897 [main] DEBUG org.apache.http.headers - http-outgoing-0 >> Accept-Encoding: gzip,deflate
00:11:45.898 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /workflows/fbf4c29cbcad4679b1a1159fff7b07f9/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%252Ftriggers%252Fmanual%252Frun&sv=1.0&sig=zxm46aQnBj3ZTKPOddnnwUgtQZoQcQfixNtXVxAJjPg HTTP/1.1[\r][\n]"
00:11:45.898 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept: */*[\r][\n]"
00:11:45.898 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: application/json[\r][\n]"
00:11:45.898 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Length: 168[\r][\n]"
00:11:45.899 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: prod-12.westeurope.logic.azure.com:443[\r][\n]"
00:11:45.899 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
00:11:45.899 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.10 (Java/1.8.0_261)[\r][\n]"
00:11:45.899 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
00:11:45.899 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"
00:11:45.900 [main] DEBUG org.apache.http.wire - http-outgoing-0 >> "{"emailadress":"jboscod@indracompany.com","emailBody":"Se voc[0xc3][0xaa] visualizar esta mensagem o bot funcionou","emailSubject":"Pend[0xc3][0xaa]ncia para lan[0xc3][0xa7]amento de horas do Jira"}"
00:11:46.340 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 401 Unauthorized[\r][\n]"
00:11:46.341 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Cache-Control: no-cache[\r][\n]"
00:11:46.343 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Pragma: no-cache[\r][\n]"
00:11:46.345 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Type: application/json; charset=utf-8[\r][\n]"
00:11:46.345 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Expires: -1[\r][\n]"
00:11:46.346 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "x-ms-request-id: westeurope:bdf621fd-4e29-456d-bf2e-a07c209bd7ff[\r][\n]"
00:11:46.347 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Strict-Transport-Security: max-age=31536000; includeSubDomains[\r][\n]"
00:11:46.348 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Date: Fri, 11 Sep 2020 03:10:47 GMT[\r][\n]"
00:11:46.348 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "Content-Length: 253[\r][\n]"
00:11:46.349 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
00:11:46.351 [main] DEBUG org.apache.http.wire - http-outgoing-0 << "{"error":{"code":"AuthorizationFailed","message":"You do not have permissions to perform action 'run' on scope '/triggers/manual/paths/'. Verify you are making the request with the appropriate HTTP method. See http://aka.ms/logic-trigger for details."}}"
00:11:46.422 [main] DEBUG org.apache.http.headers - http-outgoing-0 << HTTP/1.1 401 Unauthorized
00:11:46.423 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Cache-Control: no-cache
00:11:46.424 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Pragma: no-cache
00:11:46.425 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Type: application/json; charset=utf-8
00:11:46.427 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Expires: -1
00:11:46.427 [main] DEBUG org.apache.http.headers - http-outgoing-0 << x-ms-request-id: westeurope:bdf621fd-4e29-456d-bf2e-a07c209bd7ff
00:11:46.429 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Strict-Transport-Security: max-age=31536000; includeSubDomains
00:11:46.429 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Date: Fri, 11 Sep 2020 03:10:47 GMT
00:11:46.429 [main] DEBUG org.apache.http.headers - http-outgoing-0 << Content-Length: 253
00:11:46.546 [main] DEBUG org.apache.http.impl.execchain.MainClientExec - Connection can be kept alive indefinitely
00:11:46.546 [main] DEBUG org.apache.http.impl.auth.HttpAuthenticator - Authentication required
00:11:46.546 [main] DEBUG org.apache.http.impl.auth.HttpAuthenticator - prod-12.westeurope.logic.azure.com:443 requested authentication
00:11:46.547 [main] DEBUG org.apache.http.impl.auth.HttpAuthenticator - Response contains no authentication challenges
00:11:46.651 [main] DEBUG org.springframework.web.client.RestTemplate - Response 401 UNAUTHORIZED
00:11:46.688 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection [id: 0][route: {s}->https://prod-12.westeurope.logic.azure.com:443] can be kept alive indefinitely
00:11:46.688 [main] DEBUG org.apache.http.impl.conn.DefaultManagedHttpClientConnection - http-outgoing-0: set socket timeout to 0
00:11:46.689 [main] DEBUG org.apache.http.impl.conn.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {s}->https://prod-12.westeurope.logic.azure.com:443][total kept alive: 1; route allocated: 1 of 2; total allocated: 1 of 20]
我无法粘贴整个堆栈跟踪,因为 stackoverflow 平台不允许。
解决方案
实际上,您的请求中已经有令牌。它应该通过以下代码工作(无需禁用 SSL 或身份验证,因为您已经拥有令牌)
try {
RestTemplate restTemplate = new RestTemplate();
Map<String, String> map = new HashMap<String, String>();
map.put("emailadress", "");
map.put("emailSubject", "Pendência para lançamento de horas do Jira");
map.put("emailBody", "Se você visualizar esta mensagem o bot funcionou");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Accept",MediaType.ALL_VALUE);
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<>(map,requestHeaders);
String url = new StringBuilder()
.append("...")
.append("?api-version=").append("2016-06-01")
.append("&sp=").append("/triggers/manual/run")
.append("&sv=").append("1.0")
.append("&sig=").append("zxm46aQnBj3ZTKPOddnnwUgtQZoQcQfixNtXVxAJjPg")
.toString();
restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class);
logger.info("Bot enviado com sucesso!");
} catch (Exception e) {
logger.error("Erro ao enviar Bot.", e);
throw e;
}
推荐阅读
- django - 在 django 中创建与用户不同模型的令牌
- java - 如何在屏幕上绘制标签:MLKit 对象检测
- artificial-intelligence - TF 2 - Keras - 将两个单独训练的模型合并为一个新的集成模型
- python - Telegram bot 中的常规发送无法正常工作
- java - Netty Pipeline 无序执行
- html - 如何使用 CSS(在文本上)应用适当的渐变 alpha 蒙版?
- html - 为什么 Bootstrap 颜色不适用于行?
- python - 如何使 matplotlib 动画中的点消失?
- python - 单击模块忽略子组命令
- mysql - 开始...结束与开始交易...提交