gpt4 book ai didi

java - set 方法不适用于 HttpsURLConnection

转载 作者:行者123 更新时间:2023-12-01 05:39:25 26 4
gpt4 key购买 nike

我正在尝试用 java 发出休息请求。我在 Firefox 中使用 RestClient 测试了 Web 服务,效果非常好。

当我尝试修改 java 中的 HttpsUrlConnection 实例时,值没有更改,并且我收到 500 响应代码。

这是我的代码:

    public  String getAuthToken() throws IOException {
URL url =new URL("https://webserviceurl"); // webservice url is the url of the webservice
String data = URLEncoder.encode("username") + "=" + URLEncoder.encode("myusername","UTF-8");
data+= "&" + URLEncoder.encode("password") + "=" + URLEncoder.encode("pass","UTF-8");
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setHostnameVerifier(new AllowAllHostnameVerifier()); //this works HostName verifier changes
conn.setRequestMethod("POST"); // this doens't work. requestMethod is still set to GET
conn.setDoOutput(true); // this doesnt work. DoOutput still set on false
conn.setRequestProperty("Content-Type", "application/json"); // doens't work either
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
wr.write(data);
wr.flush();
wr.close();
//conn has a 500 response code
if (conn.getResponseCode()==200)
{
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
String token = rd.readLine();
rd.close();
return token;
}
else
return null;

}

我现在陷入困境,找不到任何东西来完成这项工作。

谢谢!

最佳答案

我实际上认为这是 HttpsURLConnection 的一个错误。当我将其更改为 HttpURLConnection 对象时,一切正常。

关于java - set 方法不适用于 HttpsURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7529136/

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