Set content-length in PostMethod of Jakarta HttpClient

Hi Folks,
I'm trying to send a HttpRequest via Jakarta's HttpClient. Everything works fine, but I could not yet figure out, how to get the content-length of my RequestBody before I set the Name-Value-Pairs via postRequest.setRequestBody(NameValuePair[] data) or after I set the Parameters via the addParameter(String paramName, String paramValue) Method.
The getRequestContentLength() Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod is protected, so I can't use it out of the PostMethod class.
Any suppestions ?
Thx for help...

The problem is solved. Instead of doing:
pw.println(postContent);
, I do:
pw.print(postContent);
...and it works. The extra newline-chars confused the webserver.
Thanks for the replies!

Similar Messages

  • Maximum size for an HttpRequest? Set Content-Length?

    Hi, I'm managing to get small strings sent from my applet to my servlet, but when I try anything bigger, I get problems. Oddly enough, the larger object can get sent to my applet from my servlet without any issues.
    Can anyone tell me if there is a maximum size for sending responses?
    Or, if I have to set the content-length property in my applet before I send my data, how do I get the size of my object so I can set it?
    thanks for any advice any of you might have

    Thanks for the pointers.
    BalusC, at first I was trying to write my object without sending it through a byteStream first (hence the q) :), tried it that way too and wouldn't work.
    I finally figured out that it wasn't the code that was the problem, but it was an upload issue (server specific). Have changed the code to sending one line of data at a time since I was converting my object to an output file in the servlet anyway. Not the best solution but it works :)
    Thanks again

  • SetRequestProperty("Content-Length", ....) is not set in the POST resquest

    Hi,
    Iam sending a POST request to a servlet. Apart from other request properties iam also setting "Content-Length" property by using the
    setRequestProperty("Content-Length", data.length) on httpconnection object. When i checked the http packtes being from the toolkit to the servlet (by using ethereal tool) i see that all other properties as appropriately set by
    "Content-Length" is not being set at all. This is causing me big problem at the server side.
    Can any one tell my why the toolkit could have droped the
    "Content-Length" property in the POST request.
    Thanks in Advance
    Raju

    :) Before Sending the data only. The code snippet is as follows:
    String data="abc";                         hc.setRequestProperty( "User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );                              hc.setRequestProperty("Content-Language", "en-US" );
    hc.setRequestProperty( "Accept", "application/octet-stream" );
    hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    hc.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length));
    hc.setRequestProperty("Cookie",sessionId);
    OutputStream out = hc.openOutputStream();
    out.write(temp.getBytes());
    out.flush();
    out.close();
    Thanks
    Rama Raju
                                            int rc = hc.getResponseCode();
                                  if (rc != HttpConnection.HTTP_OK) {
                             System.out.println("HTTP response code: " + rc);
    ....................................

  • Content-Length missing in SOAP request

    In Oracle Application Server, a SOAP request like :
    POST /eai_esn/start.swe?SWEExtSource=WebService&SWEExtCmd=Execute&WSSoap=1 HTTP/1.1
    SOAPAction: "document/http://siebel.com/marketing/import:MktgImportServiceInvokeImportJob"
    User-Agent: Axis2
    Host: 192.168.49.66:8093
    Transfer-Encoding: chunked
    Content-Type: text/xml; charset=UTF-8
    a28
    <?xml version='1.0' encoding='UTF-8'?>. . . . </soapenv:Envelope>
    0
    is rejected with an error like : "Missing body length ..."
    However , a SOAP request like :
    Content-Type: text/xml;charset=UTF-8
    SOAPAction: "document/http://siebel.com/marketing/import:MktgImportServiceInvokeImportJob"
    User-Agent: Jakarta Commons-HttpClient/3.1
    Host: 192.168.49.58:8093
    Content-Length: 2602
    <?xml ...... >
    is accepted with no error .
    Using Microsoft IIS, the first SOAP request without the 'Content-Length' is accepted just fine.
    It looks like OAS requires SOAP header to have a "Content-Length" . Is this correct ? Is there a way to change this behavior ?
    Thank you
    Gabriel Gonzalez

    Hi,
    The web service we are trying to communicate with is a third-party service that we have no control over. This service requires the name of the attribute to be in the content id field.
    See section 3.8 of the following link
    http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html
    I seem to be able to set the name, description, contentType in the SOAP adapter module I have written - but I cannot set the content-Id.
    Regards,
    Bryan

  • Importing Hotmail Address Book using Jakarta HttpClient

    Hi,
    I am using jakarta httpclient to import hotmail address book. For that i am loading the login form first and then retrieving dynamic parameters and then posting the form for authentication of user.
    I am unable to authenticate user after posting the form , it redirects me to the login page.
    Can somebody help me to figure out what i am missing in my code??
    Following is the code i have written so far:
    (To run java one will need to enter hotmail emailId and password in the loginData)
    package msn.contacts.fetcher;
    import java.io.InputStream;
    import org.apache.commons.httpclient.Header;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.cookie.CookiePolicy;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.cyberneko.html.parsers.DOMParser;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class MSNContactsFetcher {
         private String msnLoginUrl = "http://login.live.com/login.srf";
         public void login(){
              HttpClient httpClient = new HttpClient();
              httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
              int statusCode = -1;
              InputStream responseStream = null;
              DOMParser parser = null;
              InputSource source = null;
              try{
                   GetMethod loadForm = new GetMethod(msnLoginUrl);
                   loadForm.setFollowRedirects(true);
                   statusCode = httpClient.executeMethod(loadForm);
                   /*Header[] headers = loadForm.getResponseHeaders();
                   for(int i= 0;i<headers.length;i++){
                        System.out.println("Header name:: " + headers.getName() + " value::: " + headers[i].getValue());
                   System.out.println("Hotmail Status Code::: " + statusCode );          
                   if(statusCode == HttpStatus.SC_OK){
                        System.out.println("Hotmail Login Form Loaded Successfully");
                        System.out.println(loadForm.getResponseBodyAsString());
                        //System.exit(1);
                        String PPFT = null;
                        String PPSX = null;
                        String loginFormAction;
                        parser = new DOMParser();
                        responseStream = loadForm.getResponseBodyAsStream();
                        source = new InputSource(responseStream);
                        parser.parse(source);
                        Node form = parser.getDocument().getElementsByTagName("form").item(0);
                        NamedNodeMap attributes = form.getAttributes();
                        String formAction = attributes.getNamedItem("action").getNodeValue();
                        System.out.println("Form action ::: " + formAction);
                        NodeList inputElements = parser.getDocument().getElementsByTagName("input");
                        Node inputNode;
                        String name;
                        for(int i=0;i<inputElements.getLength();i++){
                             inputNode = inputElements.item(i);
                             name = inputNode.getAttributes().getNamedItem("name").getNodeValue();
                             //System.out.println(name + " " + inputNode.getAttributes().getNamedItem("value").getNodeValue() );
                             if(name.equals("PPFT")){
                                  PPFT = inputNode.getAttributes().getNamedItem("value").getNodeValue();
                             else if(name.equals("PPSX")){
                                  PPSX = inputNode.getAttributes().getNamedItem("value").getNodeValue();
                             else if(PPFT != null && PPSX!= null)
                                  break;
                             else
                                  continue;
                        System.out.println("PPFT::: " + PPFT + " PPSX::: " + PPSX );
                        NameValuePair[] loginData = {
                                  new NameValuePair("PPSX",PPSX),
                                  new NameValuePair("PwdPad","IfYouAreReadingThisYouHaveTooMuc"),
                                  new NameValuePair("login","<emailId>"),
                                  new NameValuePair("passwd","<password>"),
                                  new NameValuePair("LoginOptions","3"),                              
                                  new NameValuePair("PPFT",PPFT)                              
                        PostMethod postLoginForm = new PostMethod(formAction);                         
                        postLoginForm.setRequestBody(loginData);
                        httpClient.executeMethod(postLoginForm);
                        statusCode = postLoginForm.getStatusCode();
                        System.out.println("Status Code::: " + statusCode);
                        String responseString = postLoginForm.getResponseBodyAsString();
                        System.out.println("Response string:: " + responseString);
              }catch(Exception ex){
                   System.out.println("Exception Occurred -->> " + ex.getMessage());
                   ex.printStackTrace();
         public static void main(String[] args) {
              System.getProperties().setProperty("httpclient.useragent", " Mozilla/5.0 (Win98; I;Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4");
              System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
              System.setProperty("org.apache.commons.logging.simplelog.showdatetime","true");
              System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header","debug");
              MSNContactsFetcher msn = new MSNContactsFetcher();
              msn.login();

    are you having issues with the initial login, or is hotmail successfully taking your information, but failing to remember it when you access more of the site for address book information gathering?
    If the first part is happening, you're probably not setting up your connection within a SSL environment correctly (I'm only guessing that's what hotmail uses, as I'm not a hotmail user). There's plenty of documentation on apache's jakarta site on how to do this/troubleshoot it.
    If you're connecting, and it's not holding the information, then the cookie storing is not set up right. In that case, you may want to post a new topic more specifically relating to cookies (probably want to do it in the networking section of these forums, as it's far more pertinent there).
    I wish I could help you more, but I am far more familiar with instantiating web connections via the UrlConnection class, and not with the Jakarta Commons libraries. :(

  • HTTP PUT Request for File Uploads is returning a response header with content-length = 0

    After upgrading from CF9 to Coldfusion 10, I'm running into an odd issue, with `cURL` calls to a webservice that used to work.
    We are using an HTTP PUT Request with multipart="no" so that the request header content is the file itself, now the data is being sent properly in the content but it has a ~8k limit. This is fine for smaller files but some files are 60kb etc.
    Errors are odd too, near the 8KB limit we get a bad gateway error 502, and above that the webpage errors with a connection reset.
    It works fine with multipart="yes", but in a PUT request the file's data isn't even sent since it's looking for `httpparam formField` , the content-length from the target page's Headers show a content-length of 0 which causes `cURL` to fail with an error (56): http://curl.haxx.se/docs/manpage.html
    Here's example code to reproduce:
    <cfset sFilename = "C:\999\test4.txt">
    <cffile action="readBinary" file="#sFilename#" variable="fileRead">
    <cfset oFileInfo = GetFileInfo("#sFilename#")>
    <cfhttp           url="localhost/Clarence/diff_elt_test_output.cfm"
                                  method="PUT"
                                  username="******"
                                  password="******"
                                  multipart="yes"
                                  result="oHttp">
              <cfhttpparam type="header" name="Content-Type" value="text/plain" />
              <cfhttpparam type="header" name="Content-Length" value="#oFileInfo.Size#" />
              <cfhttpparam type="body" value="#fileRead#"/>
    </cfhttp>
    <cfdump var="#oHttp#">
    Dumping the response via GetHttpRequestData() shows that the header's content-length = 0 and content is blank.
    Whereas POST requests work fine, cURL has a -F form option which is our fallback but a solution to this would be great.
    Here's what I've tried:
    1. Changing CF post request limit sizes (64MB+)
    2. Changing IIS config web/webserver http runtime and security.request filtering request limits to much higher values
    3. AJP Connector between IIS and Tomcat has a default 8KB header limit, I changed that to 64k on both sides, still nothing
    Also am I missing something fundamental here? I thought at the network layer a packet is split up and rejoined, so large content in a http request body should work, what's wrong with Coldfusion 10?

    I am familiar with java.net package and know how to
    Read and Write Streams.
    However, what I do not know is what string
    represntation of PUT or POST resquests is?It's HttpURLConnection.setRequestMethod("PUT") or ("POST").
    Also you have to setDoOutput(true).
    Then you set the content type, possibly encode the input, set the content length, and write the file data to the stream.
    Using a Jakarta package may be easier, however.

  • Using Jakarta HttpClient API for HTTPS file upload

    Any code sample on how to upload a file via the Jakarta HttpClient API?
    I tried the PostMethod, not sure I used it right, got response msg from the server response code 301, which indicated the file had been permanently moved. What did that mean? Besides, I didn't see PutMethod have a way to specify the target uploaded file filename, it only take a File object.
    Tried the PutMethod as well, but the method I though I can use was "depreciated".
    Any idea?
    jml

    I did. The sample code use the PutMethod and specify the file object. But when I use the similar code, I got 301, which means "File permanently moved". Not sure what that mean.
    jml

  • Content-length in JSP

    Hi,
    I need to set the HTTP header 'Content-Length'
    from a JSP page, but cannot figure out how.
    // Lars Krog-Jensen

    response.setContentLength(theLength)

  • Content-length in HTTP Post request

    Hi all,
    I have a problem with a Http request. I send data in a POST to a servlet, but the KVM doesn't set the Content-Length correctly. How can I do ?
    The code :
    conn = (HttpConnection) Connector.open(m_strServer);
    conn.setRequestMethod(HttpConnection.POST);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    String requestData = "from=" + m_strOriginator + "&to=" + m_strDestinator + "&message=" + m_strMessage;
    out = conn.openDataOutputStream();
    out.write(requestData.getBytes());
    out.flush();
    in = conn.openDataInputStream();
    if (conn.getResponseCode() == 200)
         response = true;the request sended :
    POST /my_directory/test.xml HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    Transfer-Encoding: chunked
    Host: my_pc
    15
    from=8&to=9&message=J
    0
    I think that the KVM doesn't put "Content-Length:" before "15".
    Perhaps it's a bug.
    St�phane

    Maby u try to force it with:
    conn.setRequestProperty ( "Content-Length" ,
                   Integer.toString (requestData.getBytes()));
    for me it does also not work...but u never know
    lemme know if it works
    Fabian

  • Content-Length Header Missing in Http Response

    Hi folks,
    Our application uses JSPs and Servlets. To solve a TCP level probelm, we would like to ensure that each response sent from the WebLogic Server includes a content-length header. All the pages are dynamic and therefore we cannot explicitly set the content-length.
    To ensure that WebLogic has the opportunity to set this header, we have increased the response buffer size by adding a <%@ page buffer="nK" %> header to our JSPs and a response.setBufferSize call to our Servlets. The responses still do not contain a content-length header.
    Is there anything else we can do to get WebLogic to set this header?
    Thanks in advance,
    Santosh

    Anybody?

  • How to set content type while sending an email?

    Hello,
    I want to set content type text/html while send an email using org.apache.commons.httpclient api. I am using MultipartPostMethod method. and i am set using object of multipartpostmethod like post.
    and post.setRequestHeader("Content-Type","text/html").
    but it wont work.
    so please give me a proper solution.
    example::
    MultipartPostMethod post = new MultipartPostMethod("url");
    post.addParameter("msgbody","html message");
    post.setRequestHeader("Content-Type","text/html");
    Regards,
    Bhavesh Kharwa

    Actually, I'm writing a "HashMap" from servlet to applet. I have used your suggested content type "application/octet-stream" and another "appication/x-java-serialized-object" to try it. But in applet side, when I use (HashMap)in.readObject(), it always gives me a exception as:"java.util.HashMap; IllegalAccessException". Why?
    Thankd.

  • Display/content-length issue

    a custom java application merges an image to an PDF document and flattens it using iText. it sets the request header parameters through dynamic javascript and calls the adobe reader to flatten the PDF pages. after the process, the response application screen is not rendered completely. there seems to be delay before the response screen is displayed which is our concern. we suspect that incorrect content length may be a reason for this post process display issue. but, we do not set any content-length thru java.
    Q1. is there a way to remove the content-length from the response header?
    something like aHeaders for javascript. we wanted to know the syntax for aHeaders usage.
    Q2. has anyone faced a similar issue and found a fix for this issue?
    appreciate a response. thank you!

    Checkout send-error.So I can place a drective like this (assuming I have a 403.html file in that location):
    Error fn=send-error code=403 path=/opt/sun/webproxyserver/html/errors/403.html
    I assume I place this inside my Object definition for my template ... is that correct? I plan on placing it at the bottom of my template. Does its location in the Object definition matter? I am sorry but the docs are not real clear (at least to me) on hard details so forgive my questions.
    just for clarity is this a proper template definition(I have 3)?NameTrans fn="assign-name" name="BlackList" from="http://.*yahoo.*"
    NameTrans fn="assign-name" name="WhiteList-level1" from=".*://64\.215\.169\.*/.*|.*://.*gblx.net/.*"
    NameTrans fn="assign-name" name="WhiteList-default" from=".*://.*/.*"
    The one named BlackList is just for testing purposes (which I can't seem to get to work either.
    Isn't the following legal? When I have a template match it should go to this object and execute directives right? It should see and execute the deny-service right? Why is it not?
    <Object name="BlackList">
    Service fn="deny-service"
    Error fn=send-error code=403 path=/opt/sun/webproxyserver/html/errors/403.html
    </Object>
    thanks again
    Doug

  • Content length tool in Inspector and disappearing links

    I've encountered a couple of problems, one that I've solved in a haphazard way that may be of some help to some people, and one I'm still scratching my head over.
    First, often my content length in the inspector for the site page simply doesn't work. This usually happens after I've finished most of what I planned to do and have adjusted the length once or twice already. I've tried shutting down the program and/or rebooting the computer, and while that solved the problem once it usually doesn't. I also make sure for example that if I have a box, the content length is longer than the shape. Any thoughts on how this might be remedied?
    Also I noticed that if you inadvertantly move a text box or shape to the back of another element, when the links reappear they no longer work. They may work on iWeb but not on the Web site once it is published. I figured out if I make a separate text box, small just for the link, and hyperlink it there after the problem, that works just fine.
    Thx ahead of time.
    macbook    

    First, often my content length in the inspector for
    the site page simply doesn't work.
    As far as the settings for Content Height in the Inspector Page tab... it's not that they don't work...it's just that they are set incorrectly by default and the dynamically expanding page in iWeb is not reflected at all in the Content Height value (or any other value in that tab).
    To properly adjust the Content Height, it's best to wait until you have finished designing your page, but it's perfectly fine to make adjustments along the way, too. You need to go under the "View" menu and turn on the "Show Layout" feature. That way you can see the border between where the page stops and where the footer begins.
    Focus on this border for your Content Height adjustments. I usually recommend that you simply start increasing the Content Height until you start to see the footer border start moving DOWN the page. Depending on your page, you may reach values of 1000 or 2000 or even more. But once you see the footer border move down, then you know you have reached the correct value for Content Height.

  • Gzip / Content-Length HTTP-Header

    Hello,
    I'm writing an HTTP-Proxyserver, but I don't know how to get the length of a GZIPOutputStream ... I'm compressing the data, if the server does not send gzipped data:
    logger.debug("Encode as GZip data!");
    byte[] BinaryBody = new byte[8192];
    GZIPOutputStream gzipOut = new GZIPOutputStream(client.getOutputStream());
    int length;
    while ((length = in.read(BinaryBody)) != -1)
         gzipOut.write(BinaryBody, 0, length);
         gzipOut.flush();
    gzipOut.close();I often get a Nullpointer exception in the line (while ((length = in.read(BinaryBody)) != -1)
    I think it's because I don't set the Content-Length Header, but I'm not sure.
    greetings,
    Johannes

    Disable the "Use Chunked Streaming Mode" property in HTTP Transport Configuration of your business service. By default it remains enabled.
    Regards,
    Anuj

  • Content length limited to int?

    I didn't find appropriate post to this topic yet, so I hope there is no duplicates. I demand to change all content length operations to at least long with following usage big decimals. Indeed we live in century of big bytes technologies and have so limitation very annoying. Why I need to use set/get headers function to manipulate with content lengt more than Integer.MAX_VALUE. Servlet spec 2.5 must be changed to fit new data size requirements, what do you think?

    You do realize that Integer.MAX_SIZE = 2 Gigabytes, right? If you're sending that much data to a client over a single Http connection, you've got bigger problems than the max size of an int...

Maybe you are looking for

  • Security Update 2012-004 breakes my WGM in 10.6.8

    Hi at all, i'm using 10.6.8. Today installed the Security-Update 2012-004. And now i can't use the Workgroup Manager (yes latest). After loggin to Server, the program crashes. Why i'm sure that it is the Security Update and nothing else? We have here

  • Monitor/TV Output

    Does Nokia do a phone, with a nice big screen, similar to the 6280 that will run Sat-Nav but will plug into a screen & output the sat-nav info on it, if that makes sense

  • Get process ID by part of its process name

    I have a process which can change of name depending on the version of the application which runs that process. For example: myProcess64.exe myProcess65.exe Is there a way using Sigar to get the process Id by specifing something like `myProcess%` ? Ri

  • Slow iPhoto Thumbnails in iDVD

    Gang, Here's the problem. The girlfriend has a large photo library in iPhoto (not extreme!) and running iDVD on her 12" laptop was unbearable slow in scrolling through photos to add to menus. Spinning beach ball between each screen for 10 seconds or

  • Two dashboard prompts on single column expression

    Hi i need to use 2 dashboard prompts currency-transactional,operational,reporting period--ptd,ytd,qtd i have netamount ,reporting netamount,operational netamount columns i calculated ptd,qtd,ytd in rpd iam using currency and period as prompts how to