406接收String时出错

时间:2015-04-12 13:27:30

标签: android spring http-headers

我正在使用此代码将请求从Android发送到Spring服务器。 Spring中的方法必须返回一个String,但不起作用:

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错误说&#34;此请求标识的资源只能生成具有根据请求不可接受的特征的响应&#34;接受&#34;报头&#34;

它有点奇怪,因为在此之前我在我的应用程序中使用了相同的方法来记录服务器,并且它运行正常。

1 个答案:

答案 0 :(得分: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"})