gpt4 book ai didi

java - HTTP 请求以垃圾字符响应

转载 作者:行者123 更新时间:2023-12-02 10:47:16 24 4
gpt4 key购买 nike

我正在尝试向网站发送请求以从中获取一些数据。但是,响应是垃圾字符,例如:

Ì 3ú¢¸<N¤@H±ü>§#Fe®¡+K·fÐcıaOqâò;'Êù!°â<rº\¼YDóß1K`òúüb¨ÑTcíÆ

这只发生在有数据的休息时,错误也可以正常工作。响应应该如下所示(来自浏览器请求):{"d":[{"__type":"CalendarTransport:http:...","activityId":2662,"activityImportIdentifier":null,"activityType":1,"allDay":false,"attendanceMode “:1,....

这是我的代码

        try
{
HttpsURLConnection httpsURLConnection;
httpsURLConnection = (HttpsURLConnection) new URL("https", redacted, redacted).openConnection();

try
{
httpsURLConnection.setRequestMethod("POST");
}
catch (Exception e)
{
Log.d(TAG, "doInBackground: oh no (3) it's a " + e.toString());
}
httpsURLConnection.setRequestProperty("Accept-Charset", "*/*");
httpsURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
httpsURLConnection.setRequestProperty("Connection", "keep-alive");
httpsURLConnection.setRequestProperty("Content-Type", "application/json");
httpsURLConnection.setRequestProperty("Cookie", new DomainCookies(redacted).toRequestHeader());
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);

OutputStream os = httpsURLConnection.getOutputStream();

OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(redacted);
osw.flush();
osw.close();
os.close();

StringBuilder mssg = new StringBuilder();
DataInputStream inputStream;

int status = httpsURLConnection.getResponseCode();

if (status != HttpsURLConnection.HTTP_OK)
{
inputStream = new DataInputStream(httpsURLConnection.getErrorStream());
Log.d(TAG, "doInBackground: HTTP error");
}
else
{
inputStream = new DataInputStream(httpsURLConnection.getInputStream());
Log.d(TAG, "doInBackground: HTTP OK");
}
try
{
for(int c = inputStream.read(); inputStream.available() != 0; c = inputStream.read())
{
mssg.append((char)c);
}

Log.d(TAG, "doInBackground: " + mssg);
}
catch (Exception e)
{
Log.d(TAG, "doInBackground: oh no (1) it's a " + e.toString());
}
}
catch (MalformedURLException e)
{
Log.d(TAG, "onCreate: Oh no it's a " + e.toString());

}
catch (Exception e)
{
Log.d(TAG, "doInBackground: Oh no it's a " + e.toString());
}

浏览器可以很好地得到响应,这一定是我正在做的事情(或者android,但我对此表示怀疑)

最佳答案

我首先要去掉这一行:

httpsURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");

您的代码不处理这些形式的数据编码,因此不要要求服务器以这种方式对数据进行编码。

除此之外...现在是 2018 年了。停止使用 HttpsURLConnection。使用更现代且不易出错的内容,例如 OkHttp .

关于java - HTTP 请求以垃圾字符响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461602/

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