【问题标题】:time out error while connecting url连接 url 时出现超时错误
【发布时间】:2016-08-18 08:49:35
【问题描述】:

我是安卓新手。在这个应用程序中,我创建了一个登录页面,用户只有在用户名和密码与 url 中的用户名和密码匹配时才能登录,但作为响应,它显示空字符串并捕获超时错误异常。这是代码。

    public class MainActivity extends AppCompatActivity {
        Button button;
        String connectionString, params;
        PackageManager  pm;
        SharedPreferences preferences;
        DatabaseHelper mydb;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            final EditText username = (EditText) findViewById(R.id.editText);
            final EditText password = (EditText) findViewById(R.id.editText2);
            Button button = (Button) findViewById(R.id.button1);
            button.setOnClickListener((new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.button1) {
                        String userNameString = username.getText().toString();
                        String passwordString = password.getText().toString();
                        String url = "http://122.160.78.189:85/mobile/loginUser?";
                            String params = null;
                        try {
                            params = "userName=" + URLEncoder.encode(userNameString, "UTF-8") + "&password=" + URLEncoder.encode(passwordString, "UTF-8") + "&appVersion= 1.22";
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        new Mytask().execute(url, params);

                    }
                   }


            }));

        }


        class Mytask extends AsyncTask<String, Void, String> {
            // Runs in UI before background thread is called
            @Override
            protected void onPreExecute() {
                setProgressBarVisibility(true);
                // Do something like display a progress bar
            }
            // This is run in a background thread
            @Override
            protected String doInBackground(String... params) {
                return getFromServer(params[0], params[1]);
            }
            // This runs in UI when background thread finishes
            @Override
            protected void onPostExecute(String result) {
                try {
                    checkLogin(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public String getFromServer(String connectionString, String params) {
                String response = "";
                try {
                    // android.os.Debug.waitForDebugger();
                    URL url = new URL(connectionString);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    //con.setConnectTimeout(100 * 1000); //10 Seconds
                    con.setRequestMethod("POST");
                    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    con.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
                    con.setRequestProperty("Content-Language", "en-US");
                    con.setUseCaches(false);
                    con.setDoInput(true);
                    con.setDoOutput(true);
                    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                    wr.writeBytes(params);
                    wr.flush();
                    wr.close();
                    InputStream is = con.getInputStream();
                    response = read(is);
                } catch (Exception e) {
                     e.printStackTrace();
                } finally {
                    return response;
                }
            }
            private String read(InputStream in) {
                BufferedReader reader;
                StringBuilder response = new StringBuilder();
                try {
                    reader = new BufferedReader(new InputStreamReader(in));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    return response.toString();
                }
            }
        }
    }

【问题讨论】:

  • 使用volley进行网络数据传输。易于实施并为您提供重试设置
  • where user can only login if that username and password matches with username and password in the url ??????????????

标签: android


【解决方案1】:
   try {
     HttpURLConnection.setFollowRedirects(false);
     HttpURLConnection con = (HttpURLConnection) new  

     URL(url).openConnection();
    con.setRequestMethod("HEAD");


   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);

  } catch (java.net.SocketTimeoutException e) {
  return false;
 } catch (java.io.IOException e) {
  return false;

}

【讨论】:

  • 尝试使用volley库
【解决方案2】:

您可以增加连接和读取超时时间。

con.setConnectTimeout(connectiontimeout);
con.setReadTimeout(readtimeout);

你可以使用[改造]http://square.github.io/retrofit/

对于您当前的代码,此服务器响应是, {"userId":0,"userName":null,"name":null,"password":null,"role":0,"email":null,"mobile":null,"department":null," selectedState":null,"selectedmainGroup":null}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2015-08-30
    相关资源
    最近更新 更多