HttpUrlConnection在移动设备上不起作用,但在模拟器上不起作用

时间:2016-02-15 12:29:15

标签: android android-asynctask httprequest

我的移动设备突然无法连接到本地服务器。异步任务没有执行,我只是无法弄清楚原因。慢慢地,我变得非常绝望,因为在我看来,我没有改变任何事情导致这一点。 例如,这是一个无效的后台任务

public class Login extends AsyncTask<String, Void, String>{
    private String loginUrl = "http://...";

    private int loginSuccess = 0;

    public String getToken(String fromJson) throws JSONException {
        JSONObject json = new JSONObject(fromJson);


        if(json.has("api_authtoken")) {
            loginSuccess = 1;
            String appToken = json.getString("api_authtoken");
            return appToken;
        }

        else {
            return json.toString();
        }
    }

    public String doInBackground(String... arg0) {

            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String authToken;

            try {
                // get logged in to get the api_authtoken
                String email = (String) arg0[0];
                String password = (String) arg0[1];

                URL url = new URL(loginUrl);

                // Create the request and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");

                //put values of edittexts into json-Object
                JSONObject data = new JSONObject();
                try {
                    data.put("email", email);
                    data.put("password", password);
                } catch(JSONException e) {
                    Log.e("EXCEPTION", "unexpected JSON exception", e);
                    e.printStackTrace();
                }

            urlConnection.connect();
            OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(data.toString());
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            //read server response
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }

            //receive server "answer"
            try {
                return getToken(sb.toString());
            }catch(JSONException e) {
                Log.e("LOG", "unexpected JSON exception", e);
                e.printStackTrace();
            }  finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("MainActivity", "Error closing stream", e);
                    }
                }
            }

            //return sb.toString();
            return null;
        }
        catch(IOException e) {
            Log.e("LoginTask", "Error ", e);
            // If the code didn't successfully get the data, there's no point in attempting
            // to parse it.
            //forecastJsonStr = null;
            return null;
        }
    }

    public void onPostExecute(String result) {
        super.onPostExecute(result);
        //Log.v("RESULT", result);
        if(result == null) {
            CharSequence text = "no internet connection";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        if(loginSuccess == 0) {
            // if the request wasn't successful
            // give user a message via toast
            CharSequence text = "wrong password or user. please try again";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        else {
            // save token in shared preferences
            SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorToken = tokenPref.edit();
            editorToken.putString(getString(R.string.saved_auth_token), result);
            editorToken.commit();

            //save login status = 1 in shared preferences
            SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorLogin = loginPref.edit();
            editorLogin.putString(getString(R.string.saved_login), "1");
            editorLogin.commit();

            Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
            startActivity(mapsIntent);

        }
    }
}

3 个答案:

答案 0 :(得分:0)

在sdk 23中不再支持

HttpClient。你必须使用URLConnection或降级到sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')

如果您需要sdk 23,请将其添加到您的gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

HttpClient won't import in Android Studio

答案 1 :(得分:0)

你应该考虑使用HTTP库,在互联网上有很多它们,有些非常容易使用,优化和无错误。

例如,Volley(由Google制作,我非常喜欢这个),okHttp或Picasso(用于图片)。

你应该看看this

答案 2 :(得分:0)

如果你想发送(输出),例如POST或PUT请求你需要使用它: -

urlConnection.setDoOutput(true);

在您的代码中: -

public class Login extends AsyncTask<String, Void, String>{
    private String loginUrl = "http://...";

    private int loginSuccess = 0;

    public String getToken(String fromJson) throws JSONException {
        JSONObject json = new JSONObject(fromJson);


        if(json.has("api_authtoken")) {
            loginSuccess = 1;
            String appToken = json.getString("api_authtoken");
            return appToken;
        }

        else {
            return json.toString();
        }
    }

    public String doInBackground(String... arg0) {

            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String authToken;

            try {
                // get logged in to get the api_authtoken
                String email = (String) arg0[0];
                String password = (String) arg0[1];

                URL url = new URL(loginUrl);

                // Create the request and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/json");
                urlConnection.setRequestProperty("Accept", "application/json");

                urlConnection.setDoOutput(true); //  HERE

                //put values of edittexts into json-Object
                JSONObject data = new JSONObject();
                try {
                    data.put("email", email);
                    data.put("password", password);
                } catch(JSONException e) {
                    Log.e("EXCEPTION", "unexpected JSON exception", e);
                    e.printStackTrace();
                }


            OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(data.toString());
            wr.flush();

            urlConnection.connect();

            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            //read server response
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }

            //receive server "answer"
            try {
                return getToken(sb.toString());
            }catch(JSONException e) {
                Log.e("LOG", "unexpected JSON exception", e);
                e.printStackTrace();
            }  finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("MainActivity", "Error closing stream", e);
                    }
                }
            }

            //return sb.toString();
            return null;
        }
        catch(IOException e) {
            Log.e("LoginTask", "Error ", e);
            // If the code didn't successfully get the data, there's no point in attempting
            // to parse it.
            //forecastJsonStr = null;
            return null;
        }
    }

    public void onPostExecute(String result) {
        super.onPostExecute(result);
        //Log.v("RESULT", result);
        if(result == null) {
            CharSequence text = "no internet connection";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        if(loginSuccess == 0) {
            // if the request wasn't successful
            // give user a message via toast
            CharSequence text = "wrong password or user. please try again";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(MainActivity.this, text, duration);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
        }

        else {
            // save token in shared preferences
            SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorToken = tokenPref.edit();
            editorToken.putString(getString(R.string.saved_auth_token), result);
            editorToken.commit();

            //save login status = 1 in shared preferences
            SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
            SharedPreferences.Editor editorLogin = loginPref.edit();
            editorLogin.putString(getString(R.string.saved_login), "1");
            editorLogin.commit();

            Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
            startActivity(mapsIntent);

        }
    }
}
相关问题