从Android调用Web API时出现未知错误

时间:2016-02-18 11:31:43

标签: android android-asynctask

我正在尝试使用以下代码发送JSONObject作为C#Web API的输入参数

protected String doInBackground(JSONObject... companyInfo) {

    try {
        URL url;
        URLConnection urlConn;

        url = new URL(HOST_NAME + WEB_API_METHOD);

        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("Host", HOST_NAME);
        urlConn.connect();

        PrintWriter out = new PrintWriter(urlConn.getOutputStream());
        out.print(companyInfo[0]);
        out.close();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        bufferedReader.close();

        Log.i("companyInfo > ", stringBuilder.toString());
    }
    catch (Exception ex)
    {
        Log.e("Exception", ex.getLocalizedMessage());
    }
    return null;
}

调用此方法时,该方法不会执行,当我尝试捕获错误时,我没有收到有意义的消息。它显示了URL名称,就是这样。

我无法找到问题,我们将不胜感激。

这是我得到的错误

java.io.FileNotFoundException: http://MY_FULL_URL
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
     at com.fourtyninetons.NewCompanyActivity$saveCompanyProfile.doInBackground(NewCompanyActivity.java:103)
     at com.fourtyninetons.NewCompanyActivity$saveCompanyProfile.doInBackground(NewCompanyActivity.java:70)
     at android.os.AsyncTask$2.call(AsyncTask.java:295)
     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
     at java.lang.Thread.run(Thread.java:818)

拉​​克什曼。

1 个答案:

答案 0 :(得分:0)

正如this问题的解决方案中所提到的,问题在于web api方法和后端数据库。 Fiddler帮助我解决了这个问题,上面的代码工作正常。

有用的提示:当有人获得此FileNotFoundException用户POSTMAN或FIDDLER来执行该方法并找到错误时。

感谢所有试图解决此问题的人。