2014-10-12 86 views
0

我有一個android應用程序,我需要啓用用戶登錄。 我有登錄按鈕,當用戶按下按鈕時,我調用一個asyncTask將用戶數據發送到其餘服務。我可以調用該方法,但是當我調試服務器端時,我發現參數是空的,即使它作爲json對象發送到服務器。安卓系統的博客webservice - localhost glassfish

Android客戶端代碼:

class LoginByEmail extends AsyncTask<String,Void,String> { 

    @Override 
    protected String doInBackground(String... strings) { 

     String url = strings[0]; 
     String respStr = ""; 
     String userEmail = strings[1]; 
     String userPassword = strings[2]; 

     HttpResponse response; 
     JSONObject data = new JSONObject(); 

     try{ 

      HttpClient client = new DefaultHttpClient(); 
      HttpPost post = new HttpPost(url); 
      post.setHeader("Accept","application/json"); 
      post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF8"); 

      data.put("email",userEmail); 
      data.put("password",userPassword); 


      StringEntity se = new StringEntity(data.toString()); 
      post.setEntity(se); 

      response = client.execute(post); 
      respStr = EntityUtils.toString(response.getEntity()); 

     }catch (Exception e){ 
       respStr = e.getMessage().toString(); 
     } 
     return respStr; 
    } 
} 

服務器端代碼

@Path("/emailLogin") 
@POST 
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
@Produces(MediaType.APPLICATION_JSON) 
public String emailLogin(@FormParam("email") String email, @FormParam("password") String password) 
{ 
    String user = sm.loginByEmail(email,password); 
    return user; 
} 

我使用的是GlassFish作爲我的虛擬主機提供商並部署到我的休息web服務,該emailLogin功能是從其餘的web服務。

我不明白爲什麼電子郵件和密碼參數傳輸爲空。

注:的USEREMAIL和userPassword的變量不爲空,他們得到他們的價值正確

任何想法?

編輯:變量值:enter image description here

+0

你可以登錄/打印/等JSON對象的客戶端,只是爲了確認這些值不爲空? – Thufir 2014-10-12 08:42:10

回答

1

嘗試namevaluepairs中,而不是JSONObject的,這應該工作:

List<NameValuePair> data = new ArrayList<NameValuePair>(); 
data.add(new BasicNameValuePair("email",userEmail)); 
data.add(new BasicNameValuePair("password",userPassword)); 
post.setEntity(new UrlEncodedFormEntity(data)); 

編輯:

我建議你使用這個項目作爲一個圖書館。

https://github.com/matessoftwaresolutions/AndroidHttpRestService

它讓您能夠輕鬆處理的API,控制網絡的問題等

你可以找到使用的樣本存在。

你只需要:

構建您的網址 告訴組件在POST模式下執行 構建您的JSON

祝你好運!

+0

謝謝我會嘗試。你爲什麼jsonObject不工作?因爲它仍然想作爲json轉移。 +1,因爲它有效:) – Elior 2014-10-12 09:10:31

+0

我將編輯我的答案,並附上我開發的組件的鏈接。您可以發送JSONObjects,併發出GET/PUT/POST請求,控制您的互聯網連接以顯示敬酒或在設備沒有連接時執行任何操作等。它非常易於使用。請標記答案,因爲那裏是正確的,如果它真的是! :) – 2014-10-12 09:15:21