当我尝试使用REST API时出现此错误:
**java.lang.RuntimeException: Failed : HTTP error code : 406**
以下是映射请求的Controller代码:
@RequestMapping(method = RequestMethod.POST, value = "/addUser", headers = "Accept=application/json")
public @ResponseBody
Response addUser(@RequestBody String request) {
}
这是发送req -
的代码private static Response sendRequest(Request request, String restClientURL) {
Gson gs = new Gson();
//RaaSServiceLocator raasServiceLocator = RaaSServiceLocator.getInstance();
Response resp = new Response();
ObjectMapper objectMap = new ObjectMapper();
try {
String json = gs.toJson(request);
String jsonResponse = getRestRsponseJson(
getClient("POST", restClientURL), json);
resp = objectMap.readValue(jsonResponse, Response.class);
} catch (JsonParseException e) {
e.getMessage();
} catch (JsonMappingException e) {
e.getMessage();
} catch (IOException e) {
e.getMessage();
}
return resp;
}
public static String getRestRsponseJson(Object client, String jsonType) {
DefaultHttpClient defaultclient = new DefaultHttpClient();
//defaultclient.setCredentialsProvider(credentialsProvider);
StringBuffer resp = new StringBuffer();
// Changes Done
String jsonResponse = "";
BufferedReader br = null;
try {
if (client instanceof HttpPost) {
HttpPost postRequest = (HttpPost) client;
postRequest.addHeader("accept", "application/json");
StringEntity input = new StringEntity(jsonType);
postRequest.setEntity(input);
HttpResponse response = defaultclient.execute(postRequest);
String output = null;
if (response.getStatusLine().getStatusCode() != 201
&& response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent()),"UTF-8")); //findbugfix
while ((output = br.readLine()) != null) {
resp.append(output);
jsonResponse = resp.toString();
}
}
} catch (IllegalStateException e) {
e.getMessage();
} catch (IOException e) {
e.getMessage();
} finally{
if(br != null){
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return jsonResponse;
}
public static Object getClient(String clientType, String method) {
Object obj = null;
String engineContext = "http://localhost:8080/addUser";
String url = engineContext.concat(method);
System.out.println("RaaS engine URL: " + engineContext);
if ("POST".equalsIgnoreCase(clientType)) {
obj = new HttpPost(url);
} else if ("GET"
.equalsIgnoreCase(clientType)) {
obj = new HttpGet(url);
} else if ("DELETE"
.equalsIgnoreCase(clientType)) {
obj = new HttpDelete(url);
} else if ("PUT"
.equalsIgnoreCase(clientType)) {
obj = new HttpPut(url);
}
return obj;
}
为什么这个错误(406-Not Acceptable)会发生,尽管映射器应该处理映射到正确的类型?