HttpURLConnection - 它在2个用户请求后返回响应

时间:2015-01-28 05:15:27

标签: android httpurlconnection

我有一个将表单注册到Web服务器的功能! 我这样称呼它:

dialog = ProgressDialog.show(mActivity, "", getString(R.string.loading), true);
new Thread(new Runnable() {
     public void run() {
           res = register(mobile, email, pass, name, family, gender);
      }
}).start();

问题是当用户第一次点击Register button时显示Error 无响应代码,但在第二次中点击其好的
我的代码:

private String register(String mobile, String email, String pass, String name, String family, int gender) {
    StringBuffer response = new StringBuffer();
    URL url;
    HttpURLConnection connection = null;
    String urlParameters =  null;
    try {
        urlParameters = USER_FIRST_NAME+"=" + URLEncoder.encode(name, "UTF-8") +
                USER_LAST_NAME + "&=" + URLEncoder.encode(family, "UTF-8") +
                USER_EMAIL + "&=" + URLEncoder.encode(email, "UTF-8") +
                USER_MOBILE + "&=" + URLEncoder.encode(mobile, "UTF-8") +
                USER_PASSWORD + "&=" + URLEncoder.encode(pass, "UTF-8") +
                USER_GENDER + "&=" + URLEncoder.encode(String.valueOf(gender), "UTF-8");



        //Create connection
        url = new URL(registerLink);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" +
                Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response
        int responceCode = connection.getResponseCode();
        if (responceCode == HttpURLConnection.HTTP_OK) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;

            while((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
        }
        else response.append( "Error "+String.valueOf(responceCode));


    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        dialog.dismiss();
        if(connection != null) {
            connection.disconnect();
        }
        return response.toString();
    }
}

0 个答案:

没有答案