getinputstream()上的java.io.filenotfoundexception

vktxenjb  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(640)

我正在尝试从url获取InputStream,连接响应代码为 200 ,但我有个例外 FileNotFoundException 当我尝试获取InputStream时,下面是我的代码:

url = new URL("http://...");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
int status = connection.getResponseCode();
if(status >= 400){
    request = new OutputStreamWriter(connection.getOutputStream());
    request.write(params);
    request.flush();
    request.close();
    String line;
    InputStreamReader isr = new InputStreamReader(connection.getInputStream());
    BufferedReader reader = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
}

堆栈跟踪:

W/System.err: java.io.FileNotFoundException: http://...
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err:     at com.apps.topinformers.sharedreading.AddGroupMembersFragment.postText(AddGroupMembersFragment.java:112)
W/System.err:     at com.apps.topinformers.sharedreading.AddGroupMembersFragment.access$000(AddGroupMembersFragment.java:26)
W/System.err:     at com.apps.topinformers.sharedreading.AddGroupMembersFragment$PostDataAsyncTask.doInBackground(AddGroupMembersFragment.java:65)
W/System.err:     at com.apps.topinformers.sharedreading.AddGroupMembersFragment$PostDataAsyncTask.doInBackground(AddGroupMembersFragment.java:55)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:818)

问题是什么,如何调试?

osh3o9ms

osh3o9ms1#

对于@ejp的信用,我检查了以下回复:

url = new URL("http://...");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");

request = new OutputStreamWriter(connection.getOutputStream());
request.write(params);
request.flush();
request.close();
String line;

int status = connection.getResponseCode();
if(status < 400) {

    InputStreamReader isr = new InputStreamReader(connection.getInputStream());
    ...
} else{
    InputStreamReader isr = new InputStreamReader(connection.getErrorStream());
    ...
}

错误流告诉我,我请求的url的实现代码有一些问题。

0qx6xfy6

0qx6xfy62#

连接响应代码是200
不,不是。此代码中没有检查响应代码的内容。一 FileNotFoundException 表示响应代码404。
注意 setDoOutput(true) 设置要发布的方法。你不需要自己设置,

相关问题