我有一个应用程序,我通过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)
答案 0 :(得分:3)
在读取输入流之前断开了连接。移动这行代码:
connection.disconnect();
在 之后 ,您已阅读了回复流。