2013-12-18 71 views
0

我正在開發一個與我的網站進行通信的小型測試應用程序。它使用憑證製作HttpPost以查看用戶是否已註冊。Android - Asyncronous Http發佈

但是,由於某些原因,即使該應用需要花費一秒時間,該帖子仍會立即生成並且始終爲空。這是我一年前使用的一堂課,當時正在努力。

private class LoginTask extends AsyncTask<String, Integer, String> { 

    private HashMap<String, String> mData = null;// post data 
    public String serverResult = ""; 
    /** 
    * constructor 
    */ 
    public LoginTask(HashMap<String, String> data) { 
     mData = data; 
    } 

    /** 
    * background 
    */ 
    @Override 
    protected String doInBackground(String... params) { 
     byte[] result = null; 
     String str = ""; 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL 
     try { 
      // set up post data 
      ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); 
      Iterator<String> it = mData.keySet().iterator(); 
      while (it.hasNext()) { 
       String key = it.next(); 
       nameValuePair.add(new BasicNameValuePair(key, mData.get(key))); 
      } 

      post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8")); 
      HttpResponse response = client.execute(post); 
      StatusLine statusLine = response.getStatusLine(); 
      if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){ 
       result = EntityUtils.toByteArray(response.getEntity()); 
       str = new String(result, "UTF-8"); 
      } 
     } 
     catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e) { 
     } 
     serverResult = str; 
     return str; 
    } 

    /** 
    * on getting result 
    */ 
    @Override 
    protected void onPostExecute(String result) { 
     serverResult = result; 
     pb.setVisibility(View.GONE); 

     if(serverResult == "no") 
     { 
      Toast t = Toast.makeText(MainActivity.this, "Login failed. Correct username or password", Toast.LENGTH_LONG); 
      t.show(); 
     } 
     else if (serverResult.contains("email")) 
     { 
      Toast t = Toast.makeText(MainActivity.this, "HELLOOOOO", Toast.LENGTH_LONG); 
      t.show(); 
     } 
     else  
     { 
      Toast t = Toast.makeText(MainActivity.this, "Server error: " + serverResult, Toast.LENGTH_LONG); 
      t.show(); 
     } 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     pb.setProgress(progress[0]); 
    } 
} 

發送到服務器的信息絕對正確,應該檢索一些消息,但在這裏它總是空的。也許後臺進程中的某些內容是錯誤的。

+0

在str = new String(result,「UTF-8」)之前添加日誌語句;並查看結果的值。在str的catch塊之後添加另一個日誌語句。看看會發生什麼 – Prem

+0

你通過了這個?你可能會得到一些你在Logcat中沒有看到的異常,因爲你吃的是異常:'catch(Exception e){}' –

回答

1

logcat中發生了什麼?你有沒有exception

您是否將互聯網許可添加到清單中?

<uses-permission android:name="android.permission.INTERNET" /> 
+0

沒有例外,權限是問題。沒有權限必須導致設備跳過後部分,所以有一個空洞的結果。 – Kfirprods