gpt4 book ai didi

java - 如何解决 HttpURLConnection 中的 FileNotFoundException

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

我有一个应用程序,我通过 POST 方法发送短信,此方法工作正常,但有时会出现 FileNotFound 异常。请任何人告诉我出了什么问题。

下面是我的代码。谢谢

 public static String sendSMS(String data, String url1) {
URL url;

String status = "Somthing wrong ";
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(data);
wr.flush();
wr.close();
connection.disconnect();

// Get the response
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}



} catch (MalformedURLException e) {
status = "MalformedURLException Exception in sendSMS";
e.printStackTrace();
} catch (IOException e) {
status = "IO Exception in sendSMS";
e.printStackTrace();
}

return status;
}

我得到的错误

java.io.FileNotFoundException: http://.... at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)

最佳答案

您在读取输入流之前断开了连接。移动这行代码:

connection.disconnect();

在您阅读响应流之后

关于java - 如何解决 HttpURLConnection 中的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14907332/

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