简体   繁体   English

无法使用 Java 发送 Post 请求

[英]Unable to send Post request with Java

I´m trying to make a post request, according the code below:我正在尝试根据以下代码发出帖子请求:

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

At the Postman, this request works fine and don´t needs authentication, it works without login, password or token.在邮递员处,此请求工作正常,不需要身份验证,无需登录名、密码或令牌即可工作。 But, at the code above does not works.但是,在上面的代码中不起作用。

A part of the log console is below:日志控制台的一部分如下:

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]

I couldn´t paste the whole stacktrace because the stackoverflow platform don´t allow.我无法粘贴整个堆栈跟踪,因为 stackoverflow 平台不允许。

Actually you already have token in your request.实际上,您的请求中已经有了令牌。 It should work by the following code (no need disable SSL or authentication, cuz you have token already)它应该通过以下代码工作(无需禁用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM