gpt4 book ai didi

java - HttpsURLConnection 连接问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:32 25 4
gpt4 key购买 nike

我遇到了似乎无法解决的 HttpsURLConnection 问题。基本上,我正在向服务器发送一些信息,如果其中一些数据有误,服务器会向我发送一个 500 响应代码。但是,它还在响应中发送了一条消息,告诉我哪一位数据是错误的。问题是当我读入消息时消息总是空的。我认为这是因为在读取流之前总是抛出 filenotfound 异常。我对吗?我也尝试阅读错误流,但这始终是空的。这是一个 fragment :

    conn = (HttpsURLConnection) connectURL.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length",
Integer.toString(outString.getBytes().length));
DataOutputStream wr = new DataOutputStream(conn
.getOutputStream());
wr.write(outString.getBytes());
wr.flush();
wr.close();
if(conn.getResponseCode>400{

String response = getErrorResponse(conn);

public String getErrorResponse(HttpsURLConnection conn) {
Log.i(TAG, "in getResponse");
InputStream is = null;
try {

//is = conn.getInputStream();
is = conn.getErrorStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
//System.out.println(sb.toString());
return sb.toString();
// return conferenceId;
}
catch (Exception e){
e.printStackTrace();
}
}

最佳答案

所以只是为了跟进这个,这是我解决它的方法:

public static String getResponse(HttpsURLConnection conn) {
Log.i(TAG, "in getResponse");
InputStream is = null;
try {
if(conn.getResponseCode()>=400){
is = conn.getErrorStream();
}
else{
is=conn.getInputStream();
}
...read stream...
}

似乎像这样调用它们会产生一个带有消息的错误流。感谢您的建议!

关于java - HttpsURLConnection 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804295/

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