0

我有一个应用程序,我通过 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://.... 在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)

4

1 回答 1

3

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

connection.disconnect();

在您阅读响应流之后。

于 2013-02-16T05:41:30.520 回答