I want to know is there any way to forward servlet request and response from a rest webservice to a servlet..
I have a servlet on remote server from which i am calling webservice to get the request params and then i want it to forward to another servlet from that webservice.I tried some code but it does not work. Please give me suggestions if anyone had worked on it.
this is my rest web code snippet
#GET
#Path("/test")
public void requestToTelkom(#Context HttpServletRequest request,#Context HttpServletResponse response ) {
try {
// the request object is printed successfully
System.out.println(request);
// when i try to forward like this i get exceptions
RequestDispatcher rd = request
.getRequestDispatcher("BypassServlet");
rd.forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I got this exception with above code
UT010023: Request io.undertow.servlet.spec.HttpServletRequestImpl#53b21177 was not original or a wrapper
For future visitors looking for a solution. This is what helped me on a jboss eap 7 server..add allow-non-standard-wrappers="true" to your standalone.xml file in the servlet container like this:
<servlet-container name="default" allow-non-standard-wrappers="true">
<jsp-config/>
<websockets/>
</servlet-container>
Related
I am writing a personal web server.
When I send the GET request to the system, the system responds well.
But when I send the HEAD request, I get the following problems:
sun.net.httpserver.ExchangeImpl sendResponseHeaders
WARNING: sendResponseHeaders: being invoked with a content length for a HEAD
request java.io.IOException: response headers not sent yet at
jdk.httpserver/sun.net.httpserver.PlaceholderOutputStream.checkWrap(ExchangeImpl.java:448)
at
jdk.httpserver/sun.net.httpserver.PlaceholderOutputStream.write(ExchangeImpl.java:458)
at
ir.utux.service.HandleHttpResponse.writeResponse(HandleHttpResponse.java:32)
This is the code I wrote to manage the response, to simplify HEAD and GET together.
public void writeResponse(SettingModal settingModal) {
try {
switch (requestHeader.getMethod()) {
case HEAD,GET -> {
response.getResponseHeaders().set("Server", "utux HttpServer");
response.getResponseHeaders().set("Connection", "close");
response.getResponseHeaders().set("Transfer-encoding", "chunked");
response.getResponseHeaders().set("Content-Type", ContentType.HTML);
response.sendResponseHeaders(HttpStatus.SC_OK, "".length());
response.getResponseBody().write("".getBytes(StandardCharsets.UTF_8));
response.getResponseBody().flush();
response.getResponseBody().close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
I found the problem
BODY should not be sent in response to HEAD requests.
I am using javax.ws.rs.core.Response api to build and send back response to front end from my spring boot backend. I have a controller as follows.
#GetMapping(value = "/details")
public Response getDetails() throws ServiceException {
try {
//logic to get details
return Response.status(Response.Status.OK).entity(details).build();
} catch (Exception e) {
log.error(e.getMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage).build();
}
}
But I am getting 200 OK as the response status for the HTTP Request in the browser/postman even in the case of exceptions. Because of this, the ajax success block executes instead of the error block when there is an exception. Is there any way to make the error block execute in this case? I don't want to throw an exception as it sends the entire stack trace in the response.
#GetMapping is from spring mvc and spring-mvc is not JAX-RS compliant. So don't mix to use them together. Either use pure spring-mvc or pure JAX-RS . you can try to return a spring-mvc ResponseEntity (equivalent to JAX-RS Response) instead:
#GetMapping(value = "/details")
public ResponseEntity getDetails() throws ServiceException {
try {
//logic to get details
return ResponseEntity.ok(details);
} catch (Exception e) {
log.error(e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage);
}
}
I am trying to developing Facebook API using Facebook4J. It is success to get access_token from facebook as flow.
#RequestMapping(value="biztopia.facebook.redirectLogin.do")
public void redirectLogin(ModelMap model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String code = request.getParameter("code");
Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
String oauthCode = request.getParameter("code");
try {
facebook.getOAuthAccessToken(oauthCode);
AccessToken token = facebook.getOAuthAccessToken();
response.sendRedirect("biztopia.facebook.requestUserInfo.do");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#RequestMapping(value="biztopia.facebook.requestUserInfo.do")
public void requestUserInfo(ModelMap model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
try {
User user = facebook.getMe();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Recieved excetion message as flow
FacebookException{statusCode=400, response=HttpResponse{statusCode=400, responseAsString='{"error":{"message":"API calls from the server require an appsecret_proof argument","type":"GraphMethodException","code":100}}
', is=sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#446f4515, streamConsumed=true}, errorType='GraphMethodException', errorMessage='API calls from the server require an appsecret_proof argument', errorCode=100, errorSubcode=-1}
at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:93)
at facebook4j.FacebookImpl.get(FacebookImpl.java:2431)
at facebook4j.FacebookImpl.getMe(FacebookImpl.java:105)
at facebook4j.FacebookImpl.getMe(FacebookImpl.java:101)
at biztopia.facebook.web.FacebookController.requestUserInfo(FacebookController.java:292)
I found the solutions.
That is append appsecret_proof parameter at call API as "http://graph.facebook.com/me?access_token={access_token value}$appsecret_proof={appsecret_proof value}.
If you are no want append appsecret_proof parameter then you can change set to no use appsecret_proof paameter on your app management site.
The management site menu is setting>advanced>Require AppSecret Proof for Server API calls -> set to disabled.
I want to write a .jsp (tomcat5.5) that calls a web service (IIS in domain). I get an HTTP Error 401 Unauthorized. It seems that in order to call the web service you have to be a domain user. I want to allow access to the jsp only to domain users. The request.getRemoteUser() in the jsp returns null but not the domain user that calls the jsp.
From a web browser I call the web service and it works fine.
I am a bit confused with this. Can someone tell me how can the issue be resolved?
Do i have to make tomcat make SSO?
Thank you for your time.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter o = response.getWriter();
o.println("sstarting...");
o.println("user.name ".concat(System.getProperty("user.name")));
o.println("request.getRemoteUser() ".concat(request.getRemoteUser()));
try {
GetUserRoles getUserRolesRequest = new GetUserRoles();
getUserRolesRequest.setApplicationId(121);
getUserRolesRequest.setUserName("user");
GetUserRolesResponse getUserRolesResponse;
ServiceStub stub =new ServiceStub() ;
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED,"false");
getUserRolesResponse = stub.getUserRoles(getUserRolesRequest); //IT FAILS HERE 401
String str =getUserRolesResponse.getGetUserRolesResult().toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
o.println(e.getMessage());
}
}
Hi I am sending Http Request using HttpClient . I am able to call the Servlet but returning 405 status code.doPost method not allowed . tried get also same status code.
And also i am not able to get The Header in response. Do i need to forward or include the request back to Request.
//Code to Send Http Request
public void perform(Date now, long remainingRepetitions)
{
log.info("Starting the Job " + now);
System.out.println("Before try 2");
try {
HttpResponse response;
while(true){
HttpClient client = new DefaultHttpClient();
System.out.println("Http Client instantiated");
HttpPost request = new HttpPost("http://localhost:8080/Servlet");
System.out.println("Post Request created");
response = client.execute(request);
System.out.println("Http Status Code = " + response.getStatusLine().getStatusCode() );
Header headers[] = response.getAllHeaders();
for(Header h:headers){
System.out.println("New" +h.getName() + ": " + h.getValue());
}
if(response.getStatusLine().getStatusCode()==200 || response.getStatusLine().getStatusCode()== 405){
if(response.getLastHeader("JobStatus").equals("Success"))
{
break;
}
}
client.getConnectionManager().shutdown();
Thread.sleep(10000);
}
} catch (ClientProtocolException e) {
log.info(e);
} catch (IOException e) {
log.info(e);
} catch (Exception e) {
// TODO Auto-generated catch block
log.info("Exception Occured");
e.printStackTrace();
}finally{
System.out.println("finally");
}
// Servlet
private void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("Inside ProcessReqest");
try{
//some method call
resp.addHeader("JobStatus", "Success");
}catch(Exception e){
resp.addHeader("JobStatus", "Failure");
}
}
It sounds like your server doesn't support the POST method. Try using a HttpGet request instead.
POST is used to send data to a server, whereas GET is used to request information. Your code is not attempting to send any data, so I think HttpGet is what you want.
http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/HttpGet.html
If this is code both from your client and servlet, the doPost method is private, hence you're servlet will not respond to POST requests. Make your doPost method public.
I think you should change the access modifier in your post method from private. This is why it is not visible. Change the modifier to either protected or public
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("Inside ProcessReqest");
try{
//some method call
resp.addHeader("JobStatus", "Success");
}catch(Exception e){
resp.addHeader("JobStatus", "Failure");
}
}
I think the Servlet implements only doGet(). When you are calling POST method, either doPost() or service() method should be implemented by the servlet.
By default, when the servlet's service method is called, it calls the corresponding doXXX() method. If that method is not implemented by the subclass of HttpServlet, the doXXX() method in HttpServlet returns 405 Method Not Supported status code.
The snippet of doPost() method in HttpServlet is below:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_put_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
I think in your case, you have declared doPost() method as private. It's access is hidden. Modify it as protected and try.
It is not correct to have weaker access in subclass. Usually, the compiler should have given error when you compiled that servlet.
the problem is that the headers added with
HttpServletResponse.setHeader(...)
or
HttpServletResponse.addtHeader(...)
are "servlet response headers", not "HTTP headers".
So among them you find also the http headers, but what you set is not received by the client together with them.
I suggest you to use URL parameters instead of headers.