gpt4 book ai didi

java - 无法从 HttpClient 调用接收数据

转载 作者:搜寻专家 更新时间:2023-11-01 03:50:38 25 4
gpt4 key购买 nike

我正在尝试通过 HttpClient 发送 POST 请求到资源,但似乎没有数据可使用..

在将调用传递给该资源之前我有一个过滤器来验证签名并验证它,但之后什么也没有发生..在资源端没有收到数据会触发适当的异常这是我发出请求的代码

CloseableHttpResponse response = null;
StringBuilder result = new StringBuilder();
try {
CloseableHttpClient client=HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpPost request = new HttpPost(API_BASE_URL + "/generateToken");
//Set Headers
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.addHeader("Signature",URLEncoder.encode(generateSignature(),"UTF-8"));
request.addHeader("Expires", String.valueOf(timestamp));
request.addHeader("AccessKey", URLEncoder.encode(accessKey, "UTF-8"));

//Add Paramets
request.setEntity(new UrlEncodedFormEntity(parameters));

//Sends Request
response = client.execute(request);

//Read From Response
BufferedReader reader;
InputStream inputStream = response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
result.append(inputLine);
}
EntityUtils.consume(response.getEntity());

我正在发送 loginpass作为 list <NameVaulePair>参数

我的资源代码

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response getToken(@FormParam("login") String slashtagOrEmail,
@FormParam("pass") String password) {
String token = null;
try {
token = publisherService.authenticate(slashtagOrEmail, password);
return Response.ok().entity(token).build();
} catch (RemoteException | EmailNotFoundException | UsernameNotFoundException | UnknownLoginException | IncorrectPasswordException | AccountNotConfirmedException ex) {
return Response.status(Response.Status.UNAUTHORIZED).entity(ex.toString()).build();
}

}

发出请求后,我得到 UsernameNotFoundException这基本上是空的 slashtagOrEmail变量

publisherService.authenticate() 的 JUnit 测试函数给出了正确的结果,我看不出我在哪里犯了错误。

PS:这是我关于 SO 的第一个问题,请帮助我更好地构建问题,再次感谢

最佳答案

根据您的代码判断,您正在使用 ssl 验证程序,并且您可能正在连接到 http://example.com而不是 https://example.com

在这种情况下,它是 302 空响应。因为服务器正在将端口 80(默认 http 端口)请求重定向到端口 443(默认 SSL 端口)

检查响应代码是否为302。 HttpClient 不会自动重定向到页面。 https://stackoverflow.com/a/5170468/1097600

System.out.println("Response Code : " 
+ response.getStatusLine().getStatusCode());

解决方案:将 url 更改为 https://example.com

关于java - 无法从 HttpClient 调用接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29698381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com