我使用Spring Integration实现了一个REST服务。 当我尝试使用main函数手动访问服务时,它工作正常。 我还使用谷歌浏览器中的REST客户端测试了该服务,并且运行良好。但是该服务将在WebSphere服务器上使用responseCode 404返回。因此,当我在更高的环境中部署代码时,我面临着这个问题。
URL u = new URL("http://localhost:8080/MyApplication/testRestService");
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String input = jsonInput;
wout.write(input.getBytes());
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
是依赖于服务器,所以它的回复代码为404?我们需要任何服务器端配置吗?
任何建议都将受到赞赏。
答案 0 :(得分:1)
为什么对ContentType
和URLConnection
使用不同的httpClient
?
请显示您的REST服务配置:404
表示Not found
。因此,您在请求中使用(或不使用)某些选项,使其与服务器RequestMapping
不匹配。
答案 1 :(得分:0)
我尝试使用Apache HTTP Client,现在代码正在使用WebSphere。我仍然无法找到java.net.HttpURLConnection无法在WebSphere上工作的原因。
请在下面找到我的更新代码:
DefaultHttpClient httpClient = null;
HttpPost postRequest = null;
StringEntity inputEntity = null;
HttpResponse response = null;
try{
//RETREIVE WEB SERVICE URL FROM DB
String callbackURL = "http://localhost:8080/MyApplication/testRestService";
httpClient = new DefaultHttpClient();
postRequest = new HttpPost(callbackURL);
String inputData = request.toString();
inputEntity = new StringEntity(inputData);
inputEntity.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(inputEntity);
response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());
}
//System.out.println("HTTP Response Code :"+response.getStatusLine().getStatusCode());
LOGGER.debug("HTTP Response Code :"+response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
}catch(IOException ex){
ex.printStackTrace();
throw ex;
}finally{
httpClient.getConnectionManager().shutdown();
httpClient = null;
postRequest = null;
inputEntity = null;
response = null;
}