使用AsyncTask

时间:2016-12-15 10:33:48

标签: android android-asynctask httpurlconnection filenotfoundexception android-studio-2.1

我正在开发简单的登录应用程序。但是当我使用android FileNotFoundException调用(或点击)API时,我被卡住了Asynctask。我打电话后得到的状态代码也是400.但是我在错误的地方得不到它。 下面是从asynctask的doInBackground方法调用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());

之后进入catch块

如果我通过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)

谢谢: - )

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

对不起,迟到了。如果您厌倦了上述代码的调试,请尝试使用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转换为String

的Helper方法

谢谢。