#RequestMapping(value = {"sms"},method = RequestMethod.POST)
public string rplyMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
Body body = new Body.Builder("Response message").build();
Message sms =
new Message.Builder().body(body).build();
MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();
response.setContentType("application/xml");
try {
response.getWriter().print(twiml.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
}
This is how I handle the twilio response message.I want to get the content from the response message. and i want to store it in the database.How I can get the content from the response message.
Twilio developer evangelist here.
When Twilio makes a request to your application it sends the parameters encoded as application/x-www-form-urlencoded in the body of the POST request.
I've never written Java Spring MVC before, so excuse me if this isn't spot on, but I believe you can then read those parameters out of the body using the #RequestParam annotation.
#RequestMapping(value = {"sms"},method = RequestMethod.POST)
public string rplyMessage(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam("Body") String message,
#RequestParam("From") String from
) throws IOException {
storeMessage(from, message);
// respond to the request
}
The message body and the number that sent it are the parameters "Body" and "From", you can see all the available request parameters here. So, for example with the message, you set the argument to #RequestParam to the name of the parameter, then you set the type and what you want the variable to be called within the method, thus: #RequestParam("Body") String message.
I don't know how you plan to use the database, but that's what I can tell you. You can read more about #RequestParam here and see some Twilio Java and Spring tutorials here.
Let me know if that helps at all.
Related
I am developing a servlet for JAVA EE and keep getting this error "Error Viewerpage.index method has more than one entity. You must use only one entity parameter."
#ApplicationPath("REST2")
#Path("/viewer")
public class Viewerpage extends Application {
private GlobalConfiguration globalConfiguration;
private ViewerService viewerService;
#GET
#Path(value = "/viewer")
public Response index(String filename, String page, HttpServletResponse response) throws IOException {
// set headers before we write to response body
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.TEXT_HTML);
// render a page of a file based on a parameters from request
renderPage(filename, response.getOutputStream());
// complete response
response.flushBuffer();
String value = "redirect:index";
return Response.status(Response.Status.OK).entity(value).build();
}
private void renderPage(String filename, OutputStream outputStream) {
String filepath = "storage/" + filename;
// render first page
MemoryPageStreamFactory pageStreamFactory = new MemoryPageStreamFactory(outputStream);
HtmlViewOptions viewOptions = HtmlViewOptions.forEmbeddedResources(pageStreamFactory);
Viewer viewer = new Viewer(filepath);
viewer.view(viewOptions);
viewer.close();
}
}
Any ideas what cause this error?
When you declare a resource method, you can only have one parameter that is the request entity. The parameter without any annotations is considered the entity body. All other parameters must have some kind of annotation that specifies what it is and what should be injected. If they are query parameters, use #QueryParam. If it is a path parameter, use #PathParam. If it some other non-Param injectable (that is supported) e.g. HttpServletRequest, then use #Context. Other supported "Param" injectable types are #HeaderParam, #FormParam, #CookeParam, #MatrixParam, etc.
Think of the HTTP response that gets streamed to the client. You are sending it with
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.TEXT_HTML);
renderPage(filename, response.getOutputStream());
response.flushBuffer();
But then, afterwards (when the response stream at most should be closed), you try to do something that looks like building a second response:
Response.status(Response.Status.OK).entity(value).build();
As every response can have only one set of header and body you cannot go back setting headers or sending a second response entity. That is what the error is about.
I'm working with Facebook messenger app (chatbot) and I want to see what GET request I'm receiving from it. I'm using Spring Framework to start http server and ngrok to make it visible for facebook.
Facebook sending webhooks to me and i receive them, but i don't understand how to extract data from this request. Here what i get when I try HttpRequest to receive GET request. ngrok screenshot (error 500).
When I tried without HttpRequest, i had response 200 (ok).
What do i need to put to parameters of my find method to see GET request data?
My code:
#RestController
public class botAnswer {
#RequestMapping(method= RequestMethod.GET)
public String find(HttpRequest request) {
System.out.println(request.getURI());
String aaa = "222";
return aaa;
}
}
I guess HttpRequest will not help you here. For simplicity, just change HttpRequest to HttpServletRequest. You can access all query string parameters from it using request.getParameter("..."). Something like the following should work:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String handleMyGetRequest(HttpServletRequest request) {
// Reading the value of one specific parameter ...
String value = request.getParameter("myParam");
// or all parameters
Map<String, String[]> params = request.getParameterMap();
...
}
This blog post shows how to use the #RequestParam annotation as an alternative to reading the parameters from HttpServletRequest directly.
I want send を伴う出力となって to backend java code via http get request.
My get call url is http://localhost:8080/test/getID?id=%E3%82%92%E4%BC%B4%E3%81%86%E5%87%BA%E5%8A%9B%E3%81%A8%E3%81%AA%E3%81%A3%E3%81%A6
Java code:
#RequestMapping(value = "/getCaseId")
public ModelAndView showCaseId(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String msg = request.getParameter("id");
System.out.println("URL:"+msg);
return new ModelAndView("showID", "idList", null);
}
Above piece of code prints URL:ãä¼´ãåºåã¨ãªã£ã¦.
So what's change i need to do get the exact Japanese text what i have passed from front end.
Try changing your msg line to:
String msg = new String(
request.getParameter("id").getBytes(StandardCharsets.ISO_8859_1),
StandardCharsets.UTF_8
);
If that will work it means that your application server (Tomcat? jetty?) is not configured correctly to handle UTF-8 in URLs.
If you use eclipse IDE, you need to check Text File encoding. Please check with the following figure.
The problem is that the submitted query string is getting mutilated on the way into your server-side script, because getParameter() uses ISO-8559-1 instead of UTF-8.
So i modified my code as below and now its working
#RequestMapping(value = "/getCaseId")
public ModelAndView showCaseId(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String msg = new String(request.getParameter("id").getBytes("iso-8859-1"), "UTF-8")
System.out.println("URL:"+msg);
return new ModelAndView("showID", "idList", null);
}
I found this solution in http://help-forums.adobe.com/content/adobeforums/en/experience-manager-forum/adobe-experience-manager.topic.html/forum__lxgr-hi_i_am_havi.html.
Forgive me, but I may not be familiar with all the lingo necessary to ask this question properly.
I'm working on a fairly simple REST web service in Java using the org.apache.cxf.jaxrs.ext implementation of jax-rs. The method header is like this:
#GET
#Path("json/{fullAlias}")
#Produces({"application/json"})
public String json(#PathParam("fullAlias") String fullAlias, #Context MessageContext req)
where MessageContext is org.apache.cxf.jaxrs.ext.MessageContext.
There are two things I'm trying to accomplish that I can't seem to figure out:
Change the content-type if certain conditions are met (e.g. for an error)
Change the status code of the response
I've tried using changing the response by accessing it through the MessageContext:
HttpServletResponse response = req.getHttpServletResponse();
response.setContentType("text/plain")
response.setStatus("HttpServletResponse.SC_BAD_REQUEST);
But these changes have no bearing on the response sent; with or without the #Produces annotation, setting the content type inside the method doesn't affect the actual content type (With the annotation, it of course returns "application/json", without it defaults to "text/html").
I am returning a simple String as the body. I've entertained trying to return a javax.ws.rs.core.Response object to do what I want, but I don't know much about it.
How would I change the content type and/or the status codes from inside this method?
One approach is to throw a WebApplicationException, as described by Pace, which will work if you are looking to specifically handle an error condition. If you are looking to be able to change your content at any time for any reason, then you will want to take a look at returning a Response as the result of your service method rather than a String. Returning a Response gives you the greatest amount of control over how your service responds to the client request (it does require more code than returning a simple string).
Here is an example of how you would can make use of the Response object:
#GET
#Path("json/{fullAlias}")
public Response json(#PathParam("fullAlias") String fullAlias, #Context MessageContext req) {
...
if (success) {
ResponseBuilder rBuild = Response.ok(responseData, MediaType.APPLICATION_JSON);
return rBuild.build();
}
else {
ResponseBuilder rBuild = Response.status(Response.Status.BAD_REQUEST);
return rBuild.type(MediaType.TEXT_PLAIN)
.entity("error message")
.build();
}
}
I'm not sure if it's the best approach but I've done the following to solve your question #1.
public WebApplicationException createStatusException(String statusMessage) {
ResponseBuilder rb = Response.noContent();
rb = rb.type(MediaType.TEXT_PLAIN);
rb = rb.status(Status.BAD_REQUEST);
rb = rb.entity(statusMessage);
return new WebApplicationException(rb.build());
}
EDIT: I then threw the resulting WebApplicationException.
You can write your own Response Filter to change the content-type header.
#Provider
public class MimeAddingFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Content-Type", "image/png");
}
}
This filter will add the "image/png" content-type header. You can also change or remove headers in JAX-RS response filters.
I’m trying to add some data to the http header that comes back from a RESTful web service call. Is it possible to use JAX-RS or something else to add data to the response header?
Example of my method:
#GET
#Path("getAssets")
public List<Asset> getAssets(#QueryParam("page") #DefaultValue("1") String page,
#QueryParam("page_size") #DefaultValue(UNLIMITED) String pageSize) throws Exception
{
stuff…
}
Thanks for your help.
Using something such as Spring's MVC controller, you can easily get and set response headers as in the below example. A list of common headers can be found here Wikipedia - Common Headers
...
#RequestMapping(method = RequestMethod.GET)
public String myGetMethod(#PathVariable string owner, #PathVariable string pet, HttpServletResponse response) {
response.setContentType("text/html");
response.setHeader("Content-disposition","Content-Disposition:attachment;filename=fufu.png");
}
...