2015-05-03 46 views
-1

//Global.java的Android HTTP POST使用的AsyncTask java.util.concurrent.TimeoutException

package global; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpVersion; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.CoreProtocolPNames; 
import org.apache.http.params.HttpParams; 
import org.apache.http.protocol.HTTP; 

import android.content.Context; 
import android.os.AsyncTask; 

public class Global{ 

    public static final String TLD   = "local"; 
    public static final String SERVER  = "http://m.server."+TLD+"/"; 
    public static final String POST_ADD  = SERVER+"post"; 
    public static final String REQUEST_ADD = SERVER+"request"; 

    public static Context app_context  = null; 

    public static class post_to_server extends AsyncTask<ArrayList<NameValuePair>, String, String>{ 

     public String response_from_server = ""; 

     @Override 
     protected String doInBackground(ArrayList<NameValuePair>... params){ 

      try{ 

       HttpParams param = new BasicHttpParams(); 
       param.setParameter("reference", "x"); 
       param.setBooleanParameter("http.protocol.expect-continue", false); 
       param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 

       HttpPost http_post = new HttpPost(Global.POST_ADD); 

       http_post.setEntity(new UrlEncodedFormEntity(params[0], HTTP.UTF_8)); 
       http_post.setParams(param); 

       HttpClient http_client = new DefaultHttpClient(); 

       try{ 

        HttpResponse http_response = http_client.execute(http_post); 
        HttpEntity http_entity = http_response.getEntity(); 
        InputStreamReader input_stream = new InputStreamReader(http_entity.getContent()); 
        BufferedReader buffer_reader = new BufferedReader(input_stream); 

        String buffer; 

        while ((buffer = buffer_reader.readLine()) != null) { 
         response_from_server+= buffer; 
         publishProgress(); 
        } 

       }catch(ClientProtocolException e){ 
        e.printStackTrace(); 
       }catch(IOException e){ 
        e.printStackTrace(); 
       }catch(Exception e){ 
        e.printStackTrace(); 
       } 

      }catch(Exception e){ 
       e.printStackTrace(); 
      } 

      return response_from_server; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
     } 

     @Override 
     protected void onPreExecute(){ 
      super.onPreExecute(); 
     } 

     @Override 
     protected void onProgressUpdate(String... values) { 
     } 
    } 

    public static class is_connected extends AsyncTask<String, String, Boolean> { 

     protected Boolean doInBackground(String... urls) { 
      boolean response = false; 

      try{ 
       URL url = new URL(Global.SERVER); 
       HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); 
       urlc.setConnectTimeout(3000); 
       urlc.connect(); 
       if (urlc.getResponseCode() == 200) { 
        response = true; 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      return response; 
     } 

     @Override 
     protected void onProgressUpdate(String... values) { 
     } 

     @Override 
     protected void onPostExecute(Boolean result) { 
      super.onPostExecute(result); 
     } 

     @Override 
     protected void onPreExecute(){ 
      super.onPreExecute(); 
     } 

    } 
} 

//Login.java

package com.website; 

import global.Action; 
import global.Global; 
import global.Network; 

import java.util.ArrayList; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.TimeUnit; 
import java.util.concurrent.TimeoutException; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 

import com.website.R; 

import android.app.Activity; 
import android.graphics.Rect; 
import android.graphics.drawable.Drawable; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.text.SpannableStringBuilder; 
import android.text.style.ForegroundColorSpan; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.LinearLayout; 
import android.widget.Switch; 
import android.widget.TextView; 

public class Login extends Activity{ 

    //Definitions 
    //ll_ = linear layout 
    //a_ = activity 
    //link_ = clickable link 
    //btn_ = button 

    //Links 
    TextView link_login, link_register, link_forgot_password, link_forgot_username; 

    //Login Layout 
    LinearLayout ll_login; 
    EditText a_login_username, a_login_password; 
    Switch switch_logged_in; 
    Button btn_login; 

    //Register Layout 
    LinearLayout ll_register; 
    EditText a_register_email, a_register_email_confirm, a_register_username, a_register_password, a_register_password_confirm; 
    Button btn_register; 

    //Forgot password Layout 
    LinearLayout ll_forgot_password; 
    EditText a_forgot_password_username; 
    Button btn_reset_password; 

    //Forgot username Layout 
    LinearLayout ll_forgot_username; 
    EditText a_forgot_username_email; 
    Button btn_remind_username; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.login); 

     Global.app_context = getApplicationContext(); 

     setup_interface(); 
    } 

    private void setup_interface(){ 

     ll_login   = (LinearLayout) findViewById(R.id.ll_login); 
     ll_register   = (LinearLayout) findViewById(R.id.ll_register); 
     ll_forgot_password = (LinearLayout) findViewById(R.id.ll_forgot_password); 
     ll_forgot_username = (LinearLayout) findViewById(R.id.ll_forgot_username); 

     link_login   = (TextView) findViewById(R.id.link_tv_login); 
     link_register  = (TextView) findViewById(R.id.link_tv_register); 
     link_forgot_password= (TextView) findViewById(R.id.link_tv_forgot_password); 
     link_forgot_username= (TextView) findViewById(R.id.link_tv_forgot_username); 

     link_login.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       setup_login_interface(); 
       hide_n_show_interface(ll_login); 
      } 

     }); 

     link_register.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       setup_register_interface(); 
       hide_n_show_interface(ll_register); 
      } 

     }); 

     link_forgot_password.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       setup_forgot_password_interface(); 
       hide_n_show_interface(ll_forgot_password); 
      } 

     }); 

     link_forgot_username.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       setup_forgot_username_interface(); 
       hide_n_show_interface(ll_forgot_username); 
      } 

     }); 

     //default layout screen 
     setup_login_interface(); 
     hide_n_show_interface(ll_login); 
    } 

    private void setup_login_interface(){ 

     a_login_username = (EditText) findViewById(R.id.a_login_txt_uname); 
     a_login_password = (EditText) findViewById(R.id.a_login_txt_password); 
     switch_logged_in = (Switch) findViewById(R.id.a_login_switch_keep_me_logged_in); 
     btn_login   = (Button) findViewById(R.id.a_login_btn_login); 

     btn_login.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 

       if(validate_login() && Network.is_connected_to_network(Global.app_context)){ 
        new login_web().execute(); 
       } 
      } 
     }); 
    } 

    private void setup_register_interface(){ 

     a_register_email   = (EditText) findViewById(R.id.a_register_txt_email); 
     a_register_email_confirm = (EditText) findViewById(R.id.a_register_txt_email_confirm); 
     a_register_username   = (EditText) findViewById(R.id.a_register_txt_username); 
     a_register_password   = (EditText) findViewById(R.id.a_register_txt_password); 
     a_register_password_confirm = (EditText) findViewById(R.id.a_register_txt_password_confirm); 
     btn_register    = (Button) findViewById(R.id.a_register_btn_register); 

     btn_register.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 

       if(validate_registration()){ 
        //post to server, requesting if username and email are available 
       } 
      } 

     }); 

    } 

    private void setup_forgot_password_interface(){ 

     a_forgot_password_username = (EditText) findViewById(R.id.a_forgot_password_txt_username); 
     btn_reset_password   = (Button) findViewById(R.id.a_forgot_password_btn_reset_password); 

     btn_reset_password.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 

       if(validate_forgot_password()){ 
        //post to server, requesting authentication to reset password 
       } 
      }   
     }); 
    } 

    private void setup_forgot_username_interface(){ 

     a_forgot_username_email = (EditText) findViewById(R.id.a_forgot_username_txt_email); 
     btn_remind_username  = (Button) findViewById(R.id.a_forgot_username_btn_remind_username); 

     btn_remind_username.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 

       if(validate_forgot_username()){ 
        //post to server, requesting authentication as sending a reminder 
       } 
      } 

     }); 
    } 

    private void hide_n_show_interface(LinearLayout layout){ 

     ll_login.setVisibility(View.GONE); 
     ll_register.setVisibility(View.GONE); 
     ll_forgot_password.setVisibility(View.GONE); 
     ll_forgot_username.setVisibility(View.GONE); 

     layout.setVisibility(View.VISIBLE); 
    } 

    private Boolean validate_login(){ 

     if(a_login_username.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_username),a_login_username,R.drawable.ic_error); 
      return false; 
     } 

     if(a_login_username.getText().toString().length()<6 || a_login_username.getText().toString().length()>15){ 
      show_error(getString(R.string.error_invalid_username),a_login_username,R.drawable.ic_error); 
      return false; 
     } 

     if(a_login_password.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_password),a_login_password,R.drawable.ic_error); 
      return false; 
     } 

     if(a_login_password.getText().toString().length()<6 || a_login_password.getText().toString().length()>15){ 
      show_error(getString(R.string.error_password_length),a_login_password,R.drawable.ic_error); 
      return false; 
     } 

     return true; 
    } 

    private Boolean validate_registration(){ 

     if(a_register_email.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_email),a_register_email,R.drawable.ic_error); 
      return false; 
     } 

     if(!android.util.Patterns.EMAIL_ADDRESS.matcher(a_register_email.getText().toString()).matches()){ 
      show_error(getString(R.string.error_invalid_email),a_register_email,R.drawable.ic_error); 
      return false; 
     } 

     if(!a_register_email.getText().toString().matches(a_register_email_confirm.getText().toString())){ 
      show_error(getString(R.string.error_email_mismatch),a_register_email_confirm,R.drawable.ic_error); 
      return false; 
     } 

     if(a_register_username.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_username),a_register_username,R.drawable.ic_error); 
      return false; 
     } 

     if(a_register_username.getText().toString().length()<6 || a_register_username.getText().toString().length()>15){ 
      show_error(getString(R.string.error_username_length),a_register_username,R.drawable.ic_error); 
      return false; 
     } 

     if(a_register_password.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_password),a_register_password,R.drawable.ic_error); 
      return false; 
     } 

     if(a_register_password.getText().toString().length()<6 || a_register_password.getText().toString().length()>15){ 
      show_error(getString(R.string.error_password_length),a_register_password,R.drawable.ic_error); 
      return false; 
     } 

     if(!a_register_password.getText().toString().matches(a_register_password_confirm.getText().toString())){ 
      show_error(getString(R.string.error_password_mismatch),a_register_password_confirm,R.drawable.ic_error); 
      return false; 
     } 

     return true; 
    } 

    private Boolean validate_forgot_password(){ 

     if(a_forgot_password_username.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_username),a_forgot_password_username,R.drawable.ic_error); 
      return false; 
     } 

     if(a_forgot_password_username.getText().toString().length()<6 || a_forgot_password_username.getText().length()>15){ 
      show_error(getString(R.string.error_invalid_username),a_forgot_password_username,R.drawable.ic_error); 
      return false; 
     } 
     return true; 
    } 

    private Boolean validate_forgot_username(){ 

     if(a_forgot_username_email.getText().toString().matches("")){ 
      show_error(getString(R.string.error_empty_email),a_forgot_username_email,R.drawable.ic_error); 
      return false; 
     } 

     if(!android.util.Patterns.EMAIL_ADDRESS.matcher(a_forgot_username_email.getText().toString()).matches()){ 
      show_error(getString(R.string.error_invalid_email),a_forgot_username_email,R.drawable.ic_error); 
      return false; 
     } 
     return true; 
    } 

    public void show_error(String error_message, EditText txt_box, int icon){ 

     ForegroundColorSpan fgcspan = new ForegroundColorSpan(getResources().getColor(R.color.white)); 
     SpannableStringBuilder error_string_builder = new SpannableStringBuilder(error_message); 
     error_string_builder.setSpan(fgcspan, 0, error_message.length(), 0); 

     Drawable errorIcon = getResources().getDrawable(icon); 
     errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight())); 

     txt_box.setError(error_string_builder, errorIcon); 
     txt_box.requestFocus(); 
    } 

    public class login_web extends AsyncTask<Void, Void, JSONObject>{ 

     @Override 
     protected JSONObject doInBackground(Void... params) { 
      JSONObject ResponseObj = null; 

      ArrayList<NameValuePair> post_params = new ArrayList<NameValuePair>(); 
      post_params.add(new BasicNameValuePair(Action.action.toString(), Action.login.toString())); 
      post_params.add(new BasicNameValuePair(Action.username.toString(), a_login_username.getText().toString())); 
      post_params.add(new BasicNameValuePair(Action.password.toString(), a_login_password.getText().toString())); 

      Global.post_to_server post = new Global.post_to_server(); 
      post.execute(post_params); 

      try { 

       ResponseObj = new JSONObject(post.get(30, TimeUnit.SECONDS)); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } catch (ExecutionException e) { 
       e.printStackTrace(); 
      } catch (TimeoutException e) { 
       e.printStackTrace(); 
      } 

      return ResponseObj; 
     } 

     @Override 
     protected void onProgressUpdate(Void... values){ 
     } 

     @Override 
     protected void onPostExecute(JSONObject result){ 
     } 

     @Override 
     protected void onPreExecute(){ 
     } 
    } 
} 

//Network.java

package global; 

import java.util.concurrent.ExecutionException; 
import java.util.concurrent.TimeUnit; 
import java.util.concurrent.TimeoutException; 

import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.telephony.TelephonyManager; 

public class Network { 

    public static final boolean is_connected_to_network(Context app_context){ 

     boolean response = false; 

     ConnectivityManager conn_manager = (ConnectivityManager) app_context.getSystemService(Context.CONNECTIVITY_SERVICE); 

     //check for gprs connection 
     //first check, whether the device supports SIM or not 
     TelephonyManager tm = (TelephonyManager) Global.app_context.getSystemService(Context.TELEPHONY_SERVICE); 

     if(tm.getSimState()==TelephonyManager.SIM_STATE_READY){ 
      if(conn_manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()==NetworkInfo.State.CONNECTED || conn_manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()==NetworkInfo.State.CONNECTING){ 
       response = true; 
      } 
     } 

     //check for WiFi connection 
     if(conn_manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()==NetworkInfo.State.CONNECTED || conn_manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()==NetworkInfo.State.CONNECTING){ 
      response = true; 
     } 

     return response; 
    } 

    public static Boolean is_connected_to_internet(){ 

     if(!is_connected_to_network(Global.app_context)){ 
      return false; 
     } 

     Global.is_connected conn_test = new Global.is_connected(); 
     conn_test.execute(Global.SERVER); 

     try{ 
      return conn_test.get(15,TimeUnit.SECONDS); 
     }catch(InterruptedException e) { 
      e.printStackTrace(); 
     }catch(ExecutionException e) { 
      e.printStackTrace(); 
     }catch(TimeoutException e) { 
      e.printStackTrace(); 
     } 

     return false; 
    } 
} 

//error.log

05-03 22:00:49.740: W/System.err(2094):  java.util.concurrent.TimeoutException 
05-03 22:00:49.756: W/System.err(2094):  at java.util.concurrent.FutureTask.get(FutureTask.java:176) 
05-03 22:00:49.757: W/System.err(2094):  at android.os.AsyncTask.get(AsyncTask.java:503) 
05-03 22:00:49.757: W/System.err(2094):  at com.website.Login$login_web.doInBackground(Login.java:349) 
05-03 22:00:49.757: W/System.err(2094):  at com.website.Login$login_web.doInBackground(Login.java:1) 
05-03 22:00:49.757: W/System.err(2094):  at android.os.AsyncTask$2.call(AsyncTask.java:288) 
05-03 22:00:49.757: W/System.err(2094):  at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
05-03 22:00:49.758: W/System.err(2094):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
05-03 22:00:49.758: W/System.err(2094):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
05-03 22:00:49.758: W/System.err(2094):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
05-03 22:00:49.758: W/System.err(2094):  at java.lang.Thread.run(Thread.java:818) 

我不明白我在做什麼錯了?我的應用程序崩潰的每次

Response = new JSONObject(post.get(30, TimeUnit.Seconds)); 

PHP輸出

{"string":{"1":"hello","2":"world"},"int":1} 

我能夠從PHP得到響應與延遲的響應,如果我註釋掉的Android

+0

一分爲二的發言和對空檢查post.get()的返回值,你使用它的一個新的JSONObject,並非之前期望一個空的文本指針。 – greenapps

+0

這是不同的......在post.execute後,你不能使用post.get()作爲一個AsyncTask只能執行一次..但post.get()是一個壞主意,因爲它在UI線程上運行。當你嘗試在AsyncTask的doInBackground中啓動另一個AsyncTask時,你的代碼非常錯誤。 – greenapps

+0

'post = new Global.post_to_server()'請重命名該AsyncTask。把(Async)任務放在裏面,因爲你會立即發現你確實試圖啓動另一個asynctask。 – greenapps

回答

0

你應該等待響應代碼AsyncTask完成其工作。使用onPostExecute調用外部方法和方法內得到您的JSONObject

Response = new JSONObject(post.get(30, TimeUnit.Seconds));