请告诉我一个,如何解决这个问题, 有时我得到Filenotfound异常,有时候这段代码工作正常。
以下是我的代码,
public String sendSMS(String data, String url1) {
URL url;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
wr.close();
} catch (MalformedURLException e) {
status = "MalformedURLException Exception in sendSMS";
e.printStackTrace();
} catch (IOException e) {
status = "IO Exception in sendSMS";
e.printStackTrace();
}
return status;
}
答案 0 :(得分:2)
像这样重写,让我知道你是怎么做的......(注意关闭读取和写入流,如果抛出异常也会清理流)。
public String sendSMS(String data, String url1) {
URL url;
OutputStreamWriter wr = null;
BufferedReader rd = null;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (Exception e) {
if (wr != null) try { wr.close(); } catch (Exception x) {/*cleanup*/}
if (rd != null) try { rd.close(); } catch (Exception x) {/*cleanup*/}
e.printStackTrace();
}
return status;
}
答案 1 :(得分:1)
这个问题似乎是众所周知的,但出于不同的原因,所以不清楚为什么会发生这种情况。
有些线程会建议关闭OutputStreamWriter,因为刷新它是不够的,因此我会尝试在刷新后直接关闭它,因为你没有在flush和close之间的代码中使用它。
其他线程显示使用不同的连接(如HttpURLConnection)可以避免出现此问题(看一看here)
Another article建议使用URLEncoder类的静态方法编码。此方法接受一个字符串并将其编码为可以放入URL的字符串。
一些类似的问题:
URL is accessable with browser but still FileNotFoundException with URLConnection
URLConnection FileNotFoundException for non-standard HTTP port sources
祝你好运。答案 2 :(得分:0)
当服务器对HTTP请求的响应是代码404时,它返回FileNotFoundException。
检查您的网址。