How to read request body in a servlet
Hi,
can u please tell me how to read data from http request body?
thanks in advance
[How To Ask Questions The Smart Way|http://www.catb.org/~esr/faqs/smart-questions.html]
Similar Messages
-
How to read an XML from a servlet?
Hi,
I'm just starting programming and now I have a problem I can't solve. I hope someone can help me.</p>
On the client side I have a xml report and a script wich sends to the server the information I've got from the report. In this case, the 'Poliza' value.
On the server-side I have a servlet. I try to get the parameters (from the URL or from the XML), but I don't have any response on the client side. I'm sure I'm doing something wrong but I can't find the solution for solving it.
I suppose there are two ways of solving the problem.
- Make an http connetion and send just the parametes on the URL? Does anyone know how to make it?
- Reading the XML on the servlet and extract the parameters the script sent. Does anyone know how to read it?
Thank you in advance
I attach part of the code.
CLIENT SIDE
<report....>
<field sortid="0" id="Poliza" inputtype="textbox" label="Poliza" rows="1" wide="false" required="false"/>
</report>
<script name="ValidacionOnlineValidation1" script="if (0 == 0){
var szURL="http://URLServer/vonline/vonline?Poliza="+Poliza.value;
var szUserAgent = "JoP-XML_Posting_v1.0";
var m_XML;
/* In the line below, construct a XML-document that contains all the information you need to send to the server*/
var szXML = "<?xml version=\"1.0\"?><data><objects><object name=\"Poliza\" value=\"123456789\"/></objects></data>";
/* Create an instance of the MS XML Document Object Model Parser*/
m_XML= new ActiveXObject("Microsoft.XMLDOM");
m_XML.validateOnParse=true;
var bLoadResult = m_XML.loadXML(szXML);
if (bLoadResult==true) {
/*Instance of the transport object, method,...*/
var m_HttpReq = new ActiveXObject("Pocket.HTTP");
m_HttpReq.method = "GET";
m_HttpReq.Headers.create("Content-Type", "text/xml");
m_HttpReq.Headers.find ("User-Agent").Value = szUserAgent;
m_HttpReq.timeout = 150000;
/*Do the actual post of the data*/
var m_HttpResponse = m_HttpReq.GetResponse(szURL,m_XML.xml);
if (m_HttpResponse.statusCode==200) {...}
SERVER SIDE
protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String Error="";
String MSG = "";
response.setContentType("text/html");
PrintWriter out1 = response.getWriter();
Enumeration arrayparametros = request.getParameterNames();
for (;arrayparametros.hasMoreElements();){
String parametro = (String)arrayparametros.nextElement();
String valorparametro = request.getParameter(parametro);
if (parametro.equals("Poliza")){
vonlineLogica logica = new vonlineLogica();
LOGS ="on";
Respuesta respuesta = logica.procesarSolicitud(request,valorparametro);
Error = Respuesta.getError();
MSG = Respuesta.getMensaje();
else{
Error = parametro; MSG = valorparametro;
String[] values = request.getParameterValues(parametro);
out1.println("Result: " + Error + " / " + MSG);
out1.close();
}Thanks by your help Shanu.
Nevertheless, finally I tryed the easiest way (pass the parameter with 'GET'). Moreover I found why my code wasn't working. It was a fool thing. I though PDA connect throught a proxy, but it wasn't true. Whatever.
Regards.
FSG.
The final script on the xml-report is:
<report type="Validacion Online" required="false" multiple="false" attachments="false" scriptref="store://this/reportdef/script[@name='ValidacionOnlineValidation1']">
<field sortid="0" id="Poliza" inputtype="textbox" label="Poliza" rows="1" wide="false" required="false"/>
</report>
<script name="ValidacionOnlineValidation1" script="if (0 == 0)
var szURL="http://URL/vonline/vonline?parameter1=";+Poliza.value;
var m_HttpReq = new ActiveXObject("Pocket.HTTP"); m_HttpReq.timeout = 15000;
var m_HttpResponse = m_HttpReq.GetResponse(szURL,"");
window.alert(m_HttpResponse.string);
if (m_HttpResponse.statusCode==200) {....}
else {....} -
How to get "Request Body" in Direct Entitlement API ?
According to the API version 2 (http://download.macromedia.com/pub/developer/dps/entitlement/direct-entitlement-api.pdf), it said the Request Body contain the following xml document specifiying the user credentials
<credentials>
<emailAddress>[email protected]</emailAddress>
<password>stupid</password>
</credentials>
How can I get this xml in PHP? e.g. $_POST['credentials'] or somthing else?And also this xml inside "/entitlements":
Request Body: The request should contain the following xml document.
<folios>
<folio>
<productId>com.bonnier.flying.10.01.2010</productId>
<coverDate>2011-10-11T20:49:40Z</coverDate>
</folio>
<folio>
<productId>com.bonnier.flying.11.01.2010</productId>
<coverDate>2011-11-11T20:49:40Z</coverDate>
</folio>
</folios>
Or how can I get testing requests from Adobe for the API development? -
Servlet Filter - Reading Request Error
I have a servlet filter that sits in front of a webservice servlet (AXIS) - what I want the filter to do is to look at the content of the ServletRequest and if a particular string is located in the request, I want to call another service. Everything works just fine except (isin't there always an execept) that when I execute the following code in the filter:
BufferedReader inReader = request.getReader();
String line = null;
StringBuffer sbuf = new StringBuffer();
// Read the current request into a buffer
while((line = inReader.readLine()) != null) {
sbuf.append(line);
sbuf.append("\n\r");
if (sbuf.toString().indexOf("mystring") > -1) {
// I do some code
} else {
chain.doFilter(request, wrapper);
When I execute this code, at the chain.doFilter I get an "java.lang.IllegalStateException: getReader() has already been called for this request"
I know that this is because I obtained the Reader from the request. But my question is - How can I look at the request string so that I can evaluate it and not have this exception thrown..
Thx in advance...My guess is that when you do the chain.doFilter you pass the request to another resource that then tries to access the request.getInputStream method.
From the JavaDocs:
getReader
public java.io.BufferedReader getReader()
throws java.io.IOException
Retrieves the body of the request as character data using a BufferedReader. The reader translates the character data according to the character encoding used on the body. Either this method or getInputStream() may be called to read the body, not both.
Returns:
a BufferedReader containing the body of the request
Throws:
java.io.UnsupportedEncodingException - if the character set encoding used is not supported and the text cannot be decoded
IllegalStateException - if getInputStream() method has been called on this request
java.io.IOException - if an input or output exception occurred -
ERROR : Cannot read the request body while creating new calendar event api.
Hi,
I was trying to create and update the calendar event using [POST] https://outlook.office365.com/api/v1.0/me/events and [PATCH] https://outlook.office365.com/api/v1.0/me/events/<eventId> respectively.
When i try with poster or postman, I get this error
{error: {code: "ErrorInvalidRequest" message: "Cannot read the request body."} }
its not working . Any help will be appreciated.
Note: GET events and DELETE Events are working. I think the API with payload is not working.
Test Data :
URL: https://outlook.office365.com/api/v1.0/me/events/
Method: POST
JSON Data(Payload):
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
"Start": "2015-01-06T07:03:07.481Z",
"End": "2015-01-05T07:03:07.481Z",
"Attendees": [
"EmailAddress": {
"Address": "[email protected]",
"Name": "Konveen"
"Type": "Required"
Error:
"error": {
"code": "ErrorInvalidRequest",
"message": "Cannot read the request body."Hi Sahil,
I was able to make your request work fine against my Office 365 mailbox with 2 changes.
1. Can you please make sure you are adding header "Content-Type: Application/Json"?
2. Can you please make sure your end time is AFTER start time? Looks like there is a typo with your current request as the start time is on 2015-01-06 and end time is on 2015-01-05.
Hope that helps ...
Thanks,
Venkat -
How to redirect request to a servlet on another server/context
Hi
I want to redirect a request came to a servlet to another servlet on another server or atlest different context on same server.
Thanks in advance,
--NageshThanks but, now after rediriceting the request I am
not getting any ServletInputStream. Getting rintime
error as NoClassDefinitionFoundError :
ServletInputStream.That's indicative of a problem with your classpath settings.
DO I have to do anything the JSP
(which submitted the request to first servlet) after
redirecting?Nops, you shouldnt do anything after sendredirect(). The response is committed after using this method.
ram. -
How to synchronize if one servlet read a file and anothe servlet update the
How to synchronize if one servlet read a file and anothe servlet update the file at a time?
Create a class that holds the reference to the file and do the whole file manipulation just in that class. than synchronize the read and write methodes. A reference to this file handler class can be stored to the servlet context in one servlet and read out from the servlet context in the other servlet.
-
How to map every request url to one servlet
HI experts,
I have a requirement like below,
i want to map every request to a uinque servlet.
http://localhost/krish/images/kk,gif
http://localhost/krish/images/rao,gif
http://localhost/krish/images/hh,jpg
http://localhost/krish/images/srn.txt
http://localhost/krish/images/hel.wav
etc.............the no requests unlimited.
So if i write mapping in web.xml its hard to write hundreds of urls.
so i need some other process to map all these urls to one servlet ( processrequest.java)
which will process all those requests.
How do i do it?
thanks in advanceuse url-pattern as /images/* then it will call the same servlet for all URL like you mentioned
-
In Mail on my Mac how do I request a read receipt?
In Mail on my Mac how do I request a read receipt?
Greetings barendfromport,
Welcome to the Apple Support Communities!
I understand that you would like a read receipt in Mac Mail on your computer. For this question, I would refer you to the attached discussion.
How to set up read receipts in mail on OSX Mave... | Apple Support Communities
Cheers,
Joe -
How do you request a received and read report from a text message to a non-iphone
how do i request a received and read report on text messages sent to a non iphone like i did with my droid?
You cant with the native iphone app.
-
How can I insert data in the request body of a proxyService ?
I have the following xq query, I have defined a variable called context and assign the value of the xquery bellow.
<ns:Kontekst xmlns:ns20="http://skat.dk/etil/2011/02/11/">
<TransaktionsID>{fn-bea: uuid()}</TransaktionsID>
<TransaktionsTid>{fn:current-dateTime()}</TransaktionsTid>
</ns:Kontekst>
Question. is it possible to include this as part of the request body ?You can do this using the "Insert" action of OSB.Try and let us know.
http://download.oracle.com/docs/cd/E13159_01/osb/docs10gr3/tutorial/tutTransform.html#wp1068641 -
How to access request content using MultipartMessage Object
I want to take a file from the Client and upload it as a FileInputStream on the server.
I have a simple form as follows:
<form action="scan" name="scan_files" method="post"
enctype="multipart/form-data">
<input type="file" name="file1">
<input type="file" name"file2"/>
<input type="Submit" name="insert_scaned" value="Upload"/>
</form>
In my servlet I tried to use the com.sap.engine.services.servlets_jsp.lib.multipart.MultipartMessage
class to parse the form information.
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
MultipartMessage multipartMsg =
(MultipartMessage)request.getAttribute("com.sap.servlet.multipart.body");
if (multipartMsg != null) {
multipartMsg.addFormParametersToRequest();
The help said that once this is done the form information should be accessible via the
request getParameter() method. However, I can't seem to get it working?
How can I access the file so that I can parse it into a FileInputStream?
Thanks.Hi Mat,
first, welcome on SDN!
About your question:
From the APIDoc - https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/javadocs/nw04/sp12/j2ee%20engine/com/sap/engine/services/servlets_jsp/lib/multipart/multipartmessage.html - I would expect this as a solution:
MultipartMessage multipartMsg = (MultipartMessage)request.getAttribute(MultipartMessage.MULTIPART_BODY_KEY);
if (multipartMsg != null) {
for (int i = 0; i < multipartMsg.getCount(); i++) {
MultiPart mp = multipartMsg.getBodyPart(i);
// mp.getInputStream, mp.getBody() or whatever you need
Hope it helps
Detlev
PS: Please consider rewarding points for helpful answers on SDN. Thanks in advance! -
Writing InputStream in Request to OutputStream in Servlet
Hello folks,
I've implemented a servlet that i use for uploading files to a server. The file to upload can be received as an InputStream in the Request body. I'm writing the the InputStream to an OutputStream. I had this problem, that it didn't work with large files with a size greater than 500kb (approximately). The servlet was called more than once for large files and the written file had a size of approximately 128kb on the server. My code was:
final ServletInputStream in = req.getInputStream();
final OutputStream out = new FileOutputStream( file );
try
final byte[] buf = new byte[1024];
int len = 0;
while ( ( len = in.read( buf ) ) != -1 )
out.write( buf, 0, len );
buf = new byte[buf.length << 1];
finally
in.close();
out.close();
}For performance reasons, i increased the size of the buffer with every turn (buf = new byte[buf.length << 1];). This is, why it couldn't save large files! When i do not increase the size of the buffer, everything works fine.
My question is now: Why doesn't the code work with increasing the buffer?
Thanks in advance,
RobertHow did you compile that code? And why are you bitshifting the buf.length?
Well, get through a basic Java I/O tutorial and read on how to write an InputStream to an OutputStream. I personally suggest you to drop that byte block and use BufferedInputStream and BufferedOutputStream.
http://www.google.com/search?q=java+io+tutorial+site:sun.com -
How to read file from remote machine
Hello,
Hi, i would like to know how to read text file from remote machine using java source code, any code ?
Thanks very much;
Best regards
KimOn the server, perform the following steps:
Parse the request and determine the file to serve
Open a FileInputStream to the appropriate file
Obtain a reference to the Servlet OutputStream
Pipe the bytes from the file to the output stream
Flush and close the streamYou might want to call HttpServletResponse.setContentType("application/octet") to indicate to the browser that a file download will be occurring. Do so before getting the reference to the Servlet's OutputStream.
- Saish -
I am doing a project for internet control using Java,PHP and MySql.All sites should go through the proxy server only.If the HTTP header contains Content-Length,am getting the content length as below:
public class HTTPResponseReader extends HTTPMessageReader
String statusCode;
public HTTPResponseReader(InputStream istream) throws IOException, NoSuchElementException
BufferedInputStream distream = new BufferedInputStream(istream);
retrieveHeader(distream);
StringTokenizer st = new StringTokenizer(new String(HTTPMessageReader.toArray(header)));
versionProtocol = st.nextToken();
statusCode = st.nextToken();
String s;
while (st.hasMoreTokens())
s = st.nextToken();
if (s.equals("Transfer-Encoding:"))
transferEncoding = new String(st.nextToken());
if (s.equals("Content-Length:"))
contentLength = Integer.parseInt(st.nextToken());
if (s.equals("Connection:"))
connection = new String(st.nextToken());
if (connection.equals("keep-alive")) mustCloseConnection = false;
retrieveBody(distream);
}After getting the Content-Length,i used read method to read the content upto that content length.Then i concatenated the HTTP header and body and the requested site was opened.But some sites dont have Content-Length.Instead of that,Transfer-Encoding is used.I got the HTTP Response header as "Transfer-Encoding:chunked" for some sites.If this encoding is used how to get the length of the message body and how to read the content.
Can anybody help me.
Thanks in advance...
Message was edited by:
VeeraLakshmiWhy don't you use HttpUrlConnection class to retrieve data from HTTP server? This class already supports chunked encoding...
If you want to do anything by yourself then you need to read HTTP RFC and find all required information. Well in two words you may reject advanced encoding by specifying HTTP 1.0 in your request or download chunked answer manually. Read RFC anyway :)
Maybe you are looking for
-
I keep getting an error message "cannot connect to the internet." Is this a problem with my internet provider, or has anyone else had this problem.
-
Missing BPEL instances in 10.1.3.1
I have compiled and deployed a BPEL process from JDev without any errors being reported and the process appears within my domain process list. I can then initiate the process and I'm returned the page with the instance ID and the three options to loo
-
Regarding BPM Object Retrieval in PAPI API
Hi, I am using Oracle BPM10gR3 to develop BPM processes. I am having external connectivity of BPM processes with external Java application through PAPI API. I am having a BPM Object defined as "ApplicationObject" under Module which consists of instan
-
Say one has 2 partitions. Both 125 GB each. Now, I want to make one 100 GB, and the other 150 GB. I can easily make one smaller. How do I make the other larger. I do not get those "handles" between partitions that the manual implies. I only get a cor
-
Bravia KDL-40EX655 conexión inalambrica para duplicación de pantalla de mi Xperia Z10