2016-12-25 90 views
1

我想使用Android客戶端和Glassfish 4.1.1服務器(通過REST服務進行通信)實現基本身份驗證。 該服務運行良好(由POSTMAN和另一個C#-Client驗證),但在Android上,現在讓我瘋狂。 它也似乎在服務器端收到的對象是「null」,在Android端也會引發惱人的「EOFException」。 服務器端(正常工作)將對象發佈到澤西島時Android客戶端(API 23)上的java.io.EOFException

@POST 
@Consumes({MediaType.APPLICATION_JSON}) 
@Produces({MediaType.APPLICATION_JSON}) 
public Account validate(Account acc) 
{ 
    Account a = null; 
    a = Database.getInstance().getAccountByUserPw(acc); 
    return a; 
} 

Android客戶端:

public Account postData(String JSONtoSend) 
{ 

    URL url; 
    Account get = new Account(); 
    try { 
     url = new URL("http://192.xxx.xxx.x:18080/HolidayOutServer/webresources/validateacc"); 

     HttpURLConnection urlCon = (HttpURLConnection) url.openConnection(); 
     urlCon.setRequestMethod("POST"); 
     urlCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
     urlCon.setRequestProperty("Accept", "application/json; charset=UTF-8"); 

     urlCon.setDoOutput(true); // to be able to write. 
     urlCon.setDoInput(true); // to be able to read. 

     OutputStreamWriter out = new OutputStreamWriter(urlCon.getOutputStream()); 


     out.write(JSONtoSend); 

     ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream()); 
     get = (Account) ois.readObject(); 

     return get; 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 


    return get; 
} 

被稱爲內這樣的:

class help extends AsyncTask<String, Void, Account> 
{ 

    @Override 
    protected Account doInBackground(String... params) { 
     return postData(new Gson().toJson(new Account("aleqs", "lexx", -2))); 
    } 
} 

問題一言以蔽之:

  • 新澤西服務器收到null
  • Android拋出這個荒謬的EOFException。

有人可以幫忙嗎? 在此先感謝, 約翰。

回答

0

好吧,我設法在幾個小時後找到解決方案。 此代碼的工作對我來說:

try(DataOutputStream wr = new DataOutputStream(urlCon.getOutputStream())) { 
      wr.write(new Gson().toJson(new Account("aleqs", "lexx", -2)).getBytes()); 
     } 
     Reader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF-8")); 
     StringBuilder sb = new StringBuilder(); 
     for (int c; (c = in.read()) >= 0;) 
      sb.append((char)c); 
     response = sb.toString(); 
     return response; 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 



    return response; 

更改「donInBackGround」爲String的返回類型,並讓助手類擴展-STRING,太虛,與字符串。 最重要的是:檢查客戶端的屬性(例如,id,name,..)是否與SERVER SIDE中的屬性匹配。 考慮帽鎖等.. 乾杯!