当前位置: 首页 > 知识库问答 >
问题:

无法使用Java发送Post请求

松德曜
2023-03-14

我正试图根据以下代码发出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]

我无法粘贴整个stacktrace,因为stackoverflow平台不允许。

共有1个答案

裴经义
2023-03-14

实际上,您的请求中已经有令牌。它应该通过以下代码工作(无需禁用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;
}
 类似资料:
  • 这是我的控制器: 这是我的配置: 这是类别类: 如果我尝试发送内容类型为application/json和以下正文的post请求: {“id”:8,“title”:“Паа”、“engTitle”:“Pizza”、“description”:null,“menuItems”:[{“id”:4,“title”:“Паааааааааааа”和“engTitle”:“Pepperoni”、“price

  • 问题内容: 让我们假设这个网址… (此处的ID需要在POST请求中发送) 我想将其发送到服务器的,该服务器在POST方法中接受它。 如何在Java中执行此操作? 我尝试了这个: 但是我仍然不知道如何通过POST发送 问题答案: 由于原始答案中的某些类已在Apache HTTP Components的较新版本中弃用,因此,我将发布此更新。 顺便说一句,你可以在此处访问完整的文档以获取更多示例。

  • 我正在尝试使用react中的javascript fetch API将POST数据发送到另一个

  • 请求方式: "|3|2|url,content|\r" 参数: url 设置Post请求的url链接 content post请求的数据 返回值: "|3|code|data|\r" 参数: code http请求返回的成功或者错误码 成功:code = 200 获取数据失败:code = -1 http请求字段错误:code = 1 data http请求返回的数据 Arduino样例: sof

  • 我正在尝试根据下面的代码提出帖子请求: 此请求不需要身份验证,也不需要登录和密码。在邮递员那里,我可以成功地提出请求,但当我尝试执行上述代码时,我得到了: 401未经授权 我在邮递员那里模拟了错误,它给了我下面的信息: 当我在Postman中将身份验证方法更改为“No Auth”时,请求运行良好。 我想我必须在代码中设置这个选项“No Auth”,但我不知道如何设置。 我这样做: 但错误仍在继续。

  • 我正在使用Volley从我的android应用程序向运行在http://192.168.1.4:3000/Battery_Signal_Report中的本地服务器发送一个带有参数的http post请求。我很确定服务器运行正常(我用Postman成功地检查了它)。 此外,我使用ip 10.0.2.2成功地通过Android Studio的模拟器发送了请求 为了使它正常工作,我使用了各种请求实现,包