2015-04-12 58 views
0

我正在使用此代碼從Android向Spring服務器發送請求。 Spring中的方法必須返回一個字符串,但犯規的工作原理:406接收字符串時出錯

idstringtoparse=CustomHttpClient.executeHttpPost(urlGetUserIdByUsername, params); 

身爲方法executeHttpPost這樣:

public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception { 

    BufferedReader in = null; 
    try{ 
     HttpClient client = getHttpClient(); 
     HttpPost request = new HttpPost(url);   
     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters,"UTF-8");       
     formEntity.setContentEncoding(HTTP.UTF_8); 
     request.setEntity(formEntity); 
     request.setHeader("Content-Type", 
        "application/x-www-form-urlencoded;charset=UTF-8");  
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
       sb.append(line + NL); 
     } 

     String result = sb.toString(); 

     return result; 
    } 
} 

在服務器,代碼是這樣的:

@RequestMapping ("usuario/getIdUserByUsername") 
@ResponseBody 
public Long getUserIdByUsername(@RequestParam String username){ 

    Long id=(long)usuarioService.getUserIdByUsername(username); 
    usuarioService.getUserIdByUsername(username);  
    return id; 
} 

這樣,我收到一個406錯誤,指出「由此請求標識的資源只能根據請求生成不可接受的特性的響應」接受「標題」

它有點奇怪,因爲我在登錄服務器之前在我的應用程序中使用了非常相同的方法,並且它工作正常。

回答

0

這看起來可疑

request.setHeader("Content-Type", 
        "application/x-www-form-urlencoded;charset=UTF-8"); 

試試這個

request.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8"); 

隨着

@RequestMapping(value = "usuario/getIdUserByUsername", method = RequestMethod.POST, headers = {"Accept=application/x-www-form-urlencoded"}) 
+0

嘗試...沒有工作。 – Fustigador