Using HttpUrlConnection

Hi ,
I'm facing problem in Using HttpUrlConnection. When I submit a request to sun java web server 1.6 . By using the following code I request the server , The server receives the request but can not read the request body that is written on the connection output stream.
my client code :
URL page = new URL(url);
HttpURLConnection sock = (HttpURLConnection) page.openConnection();
sock.setRequestMethod("POST");
sock.setRequestProperty("Content-Length",
"" + Integer.toString(body.getBytes().length));
sock.setUseCaches(false);
sock.setDoOutput(true);
if (body.length() > 0) {
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeBytes(body);
out.flush();
out.close();
sock.connect();
BufferedReader in = new BufferedReader (new InputStreamReader(sock.getInputStream(),"Cp1256"));
int nHttpResponseCode = sock.getResponseCode();
if(nHttpResponseCode != HttpURLConnection.HTTP_OK){
System.out.println("\tHttp error:" + nHttpResponseCode );
in.close();
return nHttpResponseCode;
//receive reply
in.close();
return nHttpResponseCode;
My server code is :
String params = null;
try {
java.io.InputStream in = request.getInputStream();
byte b[] = new byte[1000]; //in.available()];
in.read(b);
char[] s = new char[b.length];
for (int i = 0; i < b.length; i++) {
if (b[i] == 0)break;
s= (char) b[i];
params = new String(s);
catch (Exception exp) {
exp.printStackTrace();
I tried to submit the request after appending the request body to the url (url like that http://ipadd/webapp/page.jsp?appndedVlaues) and retreived the appended string by calling getQueryString method and It worked well.
Does anybody faced such a problem before?
please help
Thanks

I have done things like this several times with the URLConnection class and it always seem to work. I do not, however, call the
sock.connect();
method. My code seems to work fine without it. First I get the OutputStream and write to it. Then I get the InputStream and read the data from it.
Does the "body" variable in the client code contain any data at all? I don't see it initialized anywhere with data.
I have recently developed a file upload component. It's open source, Apache License and available from our website, www . jenkov . com. It works fine, and that too reads data from the request.getInputStream(). Perhaps you can look at that code and see if you can steal some bits that can make your server code work?

Similar Messages

  • Problem using HttpURLConnection

    Hi
    I am using HttpURLConnection,to download the contents from the URL,in my application.
    When only a limitted no of threads are started then it is working fine and the stuffs are getting downloaded into a file as per my requirement However if if sponning a large number of thread or if the http server is slow then
    instead of downloading the contents slowly...the inputsteam is showing eof and the downloading is completed without actual completino.Hence i am failing to dowload all the contents{color:#008000}.(The application requires to start around 100 threads and download the contents of all the urls into a single file){color}
    Following code has been used :
    {color:#3366ff}+url = new URL(httpUrl);+
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setAllowUserInteraction(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.connect();
    appendToTempFile("");
    appendToTempFile("");
    appendToTempFile("Downloading " httpUrl);+
    in = conn.getInputStream();
    BufferedReader reader =BufferedReader(new InputStreamReader(in));
    String text;
    +while ((text = reader.readLine()) != null) {+
    if (!text.startsWith(" "))
    appendToTempFile(text);
    +}+
    +}+
    conn.disconnect();
    *{color:#000000}Please suggest me some solution.{color}*
    {color}

    1.
    Are you writing to the file with all threads at the same time? Then this could be a problem. My approach would be a consumer/producer pattern, where the download threads are the producers. They download the data and store it at a central place. Another thread, the consumer, fetches the data from this central place and writes it the file. This way you only have one thread, which is working with the file and you don't get problems like one thread is overwriting the data of another thread.
    2.
    If you start many download threads, there yould be limitations, which could result in timeouts or something like that. Some servers only allow a defined number of connections from one IP. Same goes for your browser. Firefox for example can be configured to open only a specified number of connections to one server. There are some os settings, which could be limitating, too. So you should try to not use too many threads. You could use a thread pool, for example.

  • How do you *unset*  Content-Type when using HttpURLConnection ?

    Hi people,
    I am using HttpURLConnection to set some http headers. It all works fine except that this utility is setting Content-type to text/html even though I cam not coding it to do so. I can overwrite Content-type by setting it to say, a blank, explicitly in the code, but Content-type still appears as a header (eg if I view the headers in a proxy.)
    My question is - how do you completely unset Content-Type? Here's the code snippet :
    URL url = new URL("http://mymachine-uk.uk.company.com:24331/test.html");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setIfModifiedSince(longdate); // I've set up longdate previously
    // set some headers
    con.setRequestProperty("Cache-Control","max-age=0");
    con.setRequestProperty("User-Agent","Mozilla/5.0");
    con.setRequestProperty("Keep-Alive","300");
    // I've tried hacking it like this :
    // con.setRequestProperty("Content-type",null);
    // but that just shows an empty Content-type, rather than get rid of it.
    // In a proxy window on port 24331, the three headers set explicitly above
    // all show up correctly. But Content-type:text/html is also shown, even though not coded.
    // If I fire off the same page request from a browser, Content-type ISN'T set.
    // so there must be a way of doing it :-) Help!
    thanks.
    Edited by: colin_the_aardvark on Feb 24, 2010 1:45 AM

    Hi there,
    thanks very much for trying this, the background to this is as follows :
    I am testing a software server caching product which is giving me weird behaviour; the actions the cache performs are supposed to be based on the various http headers. I am using a debug proxy ("Charles") (limited freeware-for-a-short-period) to see exactly what http headers are being set by the calling browser, or in this case, the java program. I am setting the headers directly in the code above to match what my browser is setting, as revealed by Charles. Trouble is, I'm getting different reponses back: The browser gets a http 304 from the cache and my java program gets a 200, so I have obviously failed to emulate the browser.. and the only difference I can see is that the Conetnt-Type is not set when I call the page from internet explorer, but with my program above, Content-Type is set, to a default of text/html. I want to get rid of it so I have copied the browser http header settings 100%.
    - I tried compiling this code and running it from the prompt (outside of development environment) and Content-Type is still showing up. So from what you are saying... if your attempt does not set this.. then it looks like Content-type must be getting set via some other means?
    thankyou :-)

  • Chinese character using HttpURLConnection

    Hi,
    I am trying to retrieve a chinese page using HttpURLConnection and as a result getting all chinese characters as ???.
    I know it has to be something with the fonts but cannot figure out exactly what. Any help in this regard will be great.
    Below is my sample code...
    URL connect = new URL("http://chinese.site.url");
    HttpURLConnection connect = (HttpURLConnection) connect.openConnection();
    connect.setRequestProperty("content-type", "text/html;charset=gb2312");
    BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    String inputLine;
    while ( (inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
    }

    Hi,
    I am trying to retrieve a chinese page using
    HttpURLConnection and as a result getting all chinese
    characters as ???.
    I know it has to be something with the fonts but
    cannot figure out exactly what. Any help in this
    regard will be great.
    Below is my sample code...
    URL connect = new URL("http://chinese.site.url");
    HttpURLConnection connect = (HttpURLConnection)
    connect.openConnection();
    connect.setRequestProperty("content-type",
    "text/html;charset=gb2312");
    BufferedReader in = new BufferedReader(new
    InputStreamReader(connect.getInputStream()));
    String inputLine;
    while ( (inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
    }u forgot to set the encoding for the inputstreamreader.
         public static String readTextFiles (String filename)     {
              String data="";
              File file = new File(filename);
              char[] chars = new char[(int) file.length()];
              try {
                   FileInputStream readingfile = new FileInputStream(file);
                   BufferedReader in = new BufferedReader(new InputStreamReader(readingfile, "gb2312"));
                   in.read(chars);          // org
                   in.close();
              } catch (FileNotFoundException e) {
                    System.out.println("File Not Found " + e.getMessage());
              } catch (IOException e) {
                    System.out.println("IO exce " + e.getMessage());
              data = new String(chars);
              return data;
         }     // end readTextFile

  • Unable to access URL using HttpURLConnection

    Hi,
    I am using HttpURLCOnnection class to post a data to a url(which is a web service). The webservice accepts data as text/xml.
    Following is the code snippet i used:
    URL url = new URL("http://xxx.xxx.xx.xx:8080/SampleWebService.svc");
    HttpURLConnection conn =(HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","text/xml");
    String urlStr="param1="+URLEncoder.encode(value1)+"&param2="+URLEncoder.encode(value2)
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(urlStr);
    wr.flush();
    InputStream in2 = conn.getInputStream();
    in2.close();
    wr.close();
    But when i execute the code, I am getting following error at the line(InputStream in2 = conn.getInputStream();)
    java.io.IOException: Server returned HTTP response code: 400 for URL
    Can someone please suggest a solution. Am i missing something here?
    Thanks in advance

    This may not be the cause of the problem, however I will point out that the Content-Type you are setting (text/xml) is not the content type you are sending (key=value&key=value...).
    If the webservice only accepts text/xml, then this is probably the cause of your problem.
    Another thing you could try is removing the line that sets the content type.
    Here are the request properties in some (hacky) code that I have used for sending POST requests:
                   conn.setDoOutput(true);
                   conn.setRequestProperty("Host", url.getHost());
                   conn.setRequestProperty("Referer", referer);
                   conn.setRequestProperty("Cache-Control", "max-age=0");
                   conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)");
                   conn.setRequestProperty("Cookie", cookies);Edited by: 842408 on Mar 7, 2011 10:14 AM
    Edited by: 842408 on Mar 7, 2011 10:14 AM

  • Log into Wordpress using HttpURLConnection is possible ?

    Hello, i wonder if logging into my wordpress admin account is possible using HttpUrlConnection.
    I tried to do so, but wordpress returns error:"Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress".
    I used cookie manager and handler to enable my cookies, but seems not to work. Thank you for your help !
    CookieManager cm = new java.net.CookieManager();
            CookieHandler.setDefault(cm);

    Only if you have tacacs in between,
    http://www.cisco.com/univercd/cc/td/doc/product/vpn/vpn3000/4_7/admon/access.htm#wp1507954
    Pls rate if that helps
    Regards,
    ~JG

  • How to receive 100 Continue responses using HttpURLConnection

    Hi there,
    My server returns:
    HTTP/1.1 100 Continue
    Set-Cookie: Cookie1=Value1
    Server: Microsoft-IIS/5.0
    Date: Mon, 29 Sep 2000 18:34:02 GMT
    HTTP/1.0 200 OK
    Server: Server 2
    Set-Cookie: Cookie2=Value2
    Content-Type: text/html
    I'm using HttpURLConnection to get the response.
    I need to get both responses, however HttpURLConnection only returns the 200 OK response.
    How do I get the 100 Continue response using this class? I need it to retrieve the cookie.
    Thanks.

    You can't. If you check the j2se source code you will notice that sun.net.www.http.HttpClient just drops the '100 Continue' and waits for the actual response that follows.

  • How to use HttpURLConnection

    hi! i'd like to know how to HttpURLConnection. it is an abstract class so i cannot instantiate it direcly. where is the factory to create such a damn object???
    by the way...can i use HttpURLConnection to get response from an PHP script? do i have to do the same steps as getting an html document or is it handled different?

    To make an HttpURLConnection you need to instantiate a URL object and use openConnection() which returns a URLConnection object, now if the URL use the http or https protocol you can cast it as an HttpURLConnection. Here's some sample code:
    java.net.URL address = new java.net.URL("http://www.yahoo.com");
    java.net.HttpURLConnectionYahooConn = address.openConnection();You'll need to handle java.net.MalformedURLException when you use new URL(String address)
    Cheers

  • Download PDF using httpURLConnection

    Can anyone help me on downloading PDF (or any file other than HTML) using httpURLConnection class. Reading the input stream line by line from the site using Strings causes a corrupt file download.
    Please help !!! Thanks.

    you cannot read it line by line. try reading it byte by byte
         URL url = new URL("http://yourserver.com/yourfile.pdf");
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
         InputStream in = conn.getInputStream();
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         int i;
         while((i = in.read())!= -1)
              bos.write(i);
         byte [] b = bos.toByteArray();
         FileOutputStream fos = new FileOutputStream("c:\\temp\\test.pdf");
         fos.write(b);
         fos.close();
         conn.disconnect();

  • 500 Error code while consuming web service using HTTPURLConnection

    Hi,
    I am getting an HTTP response code 500 and an IOException when I run a web service client to invoke a BMC Remedy web service (document based). I am using XML over HTTP to hit the web service as follows:
    // For Remedy
    soapAddress = "http://www.test-sislhelpdesk.siemens.co.in/arsys/services/ARService?server=bomw041a&webService=WebService_Test";
    soapEnvelope = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><SOAP-ENV:Header><AuthenticationInfo><userName>webservice</userName><password>*******</password></AuthenticationInfo></SOAP-ENV:Header><SOAP-ENV:Body><Q1:OpGetList xmlns:Q1=\"urn:WebService_Test\"><Q1:Qualification></Q1:Qualification></Q1:OpGetList></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    soapAction = "urn:WebService_Test/OpGetList";
         URL url = new URL(soapAddress);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         System.out.println ("Connection got");
         connection.setDoOutput(true);
         connection.setRequestProperty("Content-Type","text/xml");
         connection.setRequestProperty ("soapAction", "\"" + soapAction + "\"");
         OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
         System.out.println ("outputstream got");
         outputStream.write(soapEnvelope);
         outputStream.flush();
         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         String line = null;
         while ((line = reader.readLine()) != null)
              writer.write(line);
              writer.write("\n");
         System.out.println (writer);
         catch(Exception e){
              e.printStackTrace();
    I have created a .NET client proxy which seems to work well.
    I am not able to figure out as to why this code is not working. May be something wrong with the SOAP message request I am sending? But I have created this SOAP request message from the log generated for a successful hit. Any help in this regard will be highly appreciated.
    The web service is on the internet and hance is accessible to all :)
    Regards
    Vaibhav

    Tried "POST" request method, did not work.
    Actually when i hit other web services (created by me) , the code works.
    But when I hit a third party web service, it fails returning 500 error code.
    How can I extract the SOAP message returned, if any and see thinggs for myself.
    I guess there is something wrong with the request SOAP message which I am sending.

  • Timeout using HttpUrlConnection

    Dear all,
    today I found out that my software has a problem with the standard timeout using the HttpUrlConnection. I have to connect to a server and have to read a file with more than 1400 Byte. After 1460 Byte it seems that the connection is closed. I downloaded some pieces of code (http://groups.google.de/groups?hl=de&lr=&selm=b7aab076.0401230914.6c2c678f%40posting.google.com&rnum=1) and added it to my software (creating new TimeoutHandler, ...). But I still get this timeout - or it seems like it is a timeout.
    Any ideas??
    Thx,
    Sabine

    today I found out that my software has a problem with
    the standard timeout using the HttpUrlConnection.What timeout? I don't believe there is one with this class. Maybe the server side is closing the connection - and if that's the case, it's not going to matter what you do on the client end.

  • Using HttpURLConnection on particular port

    Hi,
    I am using java.net.HttpURLConnection class to make http get/post request to some server in the program. Whenever this class opens up connection with the server, it uses different ports for listening. I used netstat utility in windows to check which port it listens.
    Is there any way that whenever HttpURLConnection opens up connection with some server, it listens on partilcular port? I dont want to implement proxy server
    solution.
    Regards,
    Nirav Pradhan

    Whenever this class opens up connection with the server, it uses different ports for listeningNo it doesn't. It doesn't use any ports for listening. The server does that, on port 80, or 8080.
    Are you talking about a fixed outbound port at the client? If so, there is no mechanism in Java to get that with an HttpURLConnection. Why do you think you need it?
    Sometimes netadmins get overenthusiastic and try to control the outbound ports that can connect to certain target ports. This is completely pointless from the security viewpoint or indeed any viewpoint, and imposes unnecessary or in this case impossible requirements on the developers.
    If this is your situation, tell them I said so.

  • SocketException: Connection reset , using HttpURLConnection

    hello everybody, i'm using this to read a xml from internet:
           URL url;
                HttpURLConnection urlcon;
                url = new URL (urlString);
                System.out.print("Connecting ....\t");
                urlcon = (HttpURLConnection)url.openConnection();
                if(!urlcon.getResponseMessage().equals("OK"))
                    return -1;
                System.out.println("Done!");it gives me:
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read1(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unkno
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at java.net.HttpURLConnection.getResponseMessage(Unknown Source)
    when i do urlcon.getResponseMessage()....
    Any ideas why this happens?
    PS: when i try the same URL in a browser, it opens the file fine .....

    My suggestion is run that with Wireshark (ethereal)
    monitoring the data. That way you can see what is
    really going on in the traffic and compare that to
    the browsers traffic. It's possible that the server
    is attempting to block bots, and I think Java tells
    the server that it is a JRE connecting and not a
    normal browser. There are ways to get around that
    though if that is the issue.You were right, the first thing i tried was to set the user-agent property in the request, and that was it, looks like the server was blocking me, thx everybody

  • Communication with servlet using HTTPURLConnection

    Hi Again,
    well..trying to connect to a servlet using the HTTPURLConnection class.
    but the servlet is found (as i have put a system.out in init method of the servlet and that gets printed correctly).my problem is that the doget method does not get invoked.
    following is the code:
    client side:
    public class test
    public test()
    ObjectOutputStream outs=null;
    try
    URL url = new URL("http://127.0.0.1:7001/DataFetchServlet");
    HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
    System.out.println(urlcon.toString());
    urlcon.setRequestProperty("Content-Type","application/octet-stream");
    urlcon.setRequestMethod("GET");
    urlcon.setDoInput(true);
    urlcon.setDoOutput(true);
    urlcon.setUseCaches(true);
    outs = new ObjectOutputStream(urlcon.getOutputStream());
    String str = new String("hello");
    outs.writeObject(str);
    ObjectInputStream inp = new ObjectInputStream (urlcon.getInputStream());//********************
    outs.flush();
    outs.close();
    catch(Exception e)
         e.printStackTrace();
    //******************** THIS LINE GIVES A FILENOTFOUND EXCEPTION
    I am sure the servlet is found before the object is written but after the getInputStream it throws the excpetion..
    can anyone help?????
    THanx in advance

    urlcon.connect();

  • HTTP digest Authentication, using HttpURLConnection

    Hi,
    My requirement is simple, my stanalone applicaiton creates a XML request sends that to a web Application. Now to do this the Web application needs a HttpDigest Authentication. To do this wat we are doing is create a http url connection and get 401 response and then use that ot create the digest. to accomplish this the same urlConnection need to be used, else the new URL connection will send a new request. But in HttpUrlConnection there is a limitation that it can be used for only single request-response cycle.... can anybody suggest on this, wats the best practice to do HTTP digest authentication while communicating from a Stand alone application to a web application........................

    I would open a support case to get clarification on whether DIGEST is supported. According to the WLS 8.1 book I found on google, it looks like it may have been supported in 8.1:
    http://books.google.com/books?id=TiAKHpPHpHIC&pg=PA836&lpg=PA836&dq=WebLogic+Digest+Authentication&source=web&ots=ciJMQOXm2q&sig=oJGOs-J5snfFGt_hWSPi-FXyERQ&hl=en&sa=X&oi=book_result&resnum=10&ct=result
    If that is the case, it is unlikely that they removed it, it just may not be documented well as it is very uncommon.

Maybe you are looking for

  • Attempted Iphone 4 update to latest firmware update "failed"

    Ive attempted to update the Iphone to the latest firmware update  and it has failed 3 times, the final time it looked as though it worked but stopped and went into new mode to go-back to Restore to old  setting. Now it is locked up and asking me for

  • Firefox 4 hangs when attempting to view the Applications tab in Preferences

    Firefox 4 under MacOS X 10.6.6 hangs when I click to select the "Applications" tab on the Preferences dialog. It never paints the pane. When this happens, it consumes 60% CPU. Running dtruss against the running process shows a little activity, but no

  • Dev 6.0 to 8iEE Connection on same NT Box

    Hi, Seems from what I have read it is a common problem to connect Dev 6.0 to 8i on same NT Box. Reckon we all need this process documented. I am currently unsuccessful in this task and so need some help. 1. Load NT with TCP/IP machine name "delly" 2.

  • Free PowerShell eBooks - living post?

    http://powershell.com/cs/blogs/ebookv2/default.aspx http://powershell.org/wp/ebooks/ Maybe we should have a list of all the free resources, MVAs, youtube, etc. Maybe even a free vs paid section, as there are some books and things the people always

  • Remove role from user

    HI how do i remove a role from a user when he id terminated or disabled. I am assigning a role in the following way during creation with the help of a rule <setvar name='newuser.waveset.roles'> <filterdup> <appendAll> <ref>accounts[Lighthouse].roles<