filenotfoundException使用asynctask调用Restful API时



我正在开发简单的登录应用程序。但是我被卡在使用Android Asynctask打电话(或击中)API时获得FileNotFoundException的点。另外,我在打电话后获得的状态代码为400。但是我在出错的地方没有得到它。以下是从doinbackground方法asynctask调用API的代码。

@Override
    protected JSONObject doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
        BufferedWriter writer = null;
        OutputStream out = null;
        try
        {
            String email = params[0];
            String password = params[1];

            URL url = new URL("http://192.168.1.67:8080/eye/api/login");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(10000);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Accept", "application/json");

            List<NameValuePair> loginCredentials = new ArrayList<>();
            loginCredentials.add(new BasicNameValuePair("username", email));
            loginCredentials.add(new BasicNameValuePair("password", password));
            out = urlConnection.getOutputStream();
            writer = new BufferedWriter(
                    new OutputStreamWriter(out, "UTF-8"));
            writer.write(getQuery(loginCredentials));
            writer.flush();
            int statusCode = urlConnection.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK)
            {
                Log.d("LoginActivity", "Connection failed: StatusCode: " + statusCode);
            }
            else
            {
                Log.d("LoginActivity", "Connection Success: StatusCode: " + statusCode);
            }
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            responseText = getResponseText(in);
            return new JSONObject(responseText);
          }
            catch (Exception e)
          {
            e.printStackTrace();
          }
           return null;
       }

P.S。: - getQuery()是将附加&amp;编码URL参数和 getResponseText()是读取服务器响应的函数。仅供参考,执行的控制进入线InputStream in = new BufferedInputStream(urlConnection.getInputStream());

之后进入捕获块

另外,如果我通过Postman击中此特定URL,我将获得200(http ok)作为响应代码。

这是错误日志的说明:

12-15 16:24:07.028  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ java.io.FileNotFoundException: http://192.168.1.67:8080/eye/api/login
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:206)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at krixi.com.spanpumploginhit.Login$AsyncCheckLogin.doInBackground(Login.java:213)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at krixi.com.spanpumploginhit.Login$AsyncCheckLogin.doInBackground(Login.java:153)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-15 16:24:07.029  26145-26182/krixi.com.spanpumploginhit W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

谢谢: - )

如果您在localhost上运行,则在地址中使用10.0.2.2: [portnumber]。

对不起,回答迟到。如果您不受上述调试,请尝试使用HttpClient而不是HttpURLConnection。它对我有用。只需在您的doinbackground()中尝试以下代码。

        String email = params[0];
        String password = params[1];
        InputStream inputStream = null;
        String result = "";
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost("http://192.168.1.67:8080/eye/api/login");
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("username", email);
            jsonObject.accumulate("password", password);
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            // 10. convert inputstream to string
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        }catch (Exception e){
        }

不要忘记在应用程序级别build.gradle

中添加以下依赖关系
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'

让我知道它是否有效!

P.S。: - ConvertInputStreamToString(InputStream)是将InputStream转换为字符串

的辅助方法

谢谢。

最新更新