【问题标题】:Unable to send Post request with Java无法使用 Java 发送 Post 请求
【发布时间】:2020-12-29 12:54:20
【问题描述】:

我正在尝试根据以下代码发出发布请求:

        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;
    }

在邮递员处,此请求可以正常工作并且不需要身份验证,它无需登录名、密码或令牌即可工作。但是,上面的代码不起作用。

部分日志控制台如下:

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 平台不允许。

【问题讨论】:

  • 错误是什么?是 CORS 还是CSFR?
  • 这可能是由于https。您是否在邮递员中关闭了 ssl 验证(这将允许 https 请求通过)?你可以发布堆栈跟踪吗?请参阅此答案,了解如何将证书与 RestTemplate stackoverflow.com/a/41618150/1410671 一起使用
  • 我使用堆栈跟踪编辑问题。
  • 根据您的评论,我对代码进行了一些更改,但仍然得到 401 UNAUTHORIZED

标签: java spring-boot api rest


【解决方案1】:

实际上,您的请求中已经有令牌。 它应该通过以下代码工作(无需禁用 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;
}

【讨论】:

  • 欢迎,很高兴听到这个消息
猜你喜欢
  • 2016-10-16
  • 2022-01-15
  • 2013-03-08
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多