HttpRequest

Experts,

I need to use a HttpRequest method to send to Webserver A and get the response message back from Webserver A. Can you provide the codes to enahnce my knowledge.

Thank You

Jason
jason101799Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Venci75Connect With a Mentor Commented:
check this code - it is not the full code, but should give you the idea how to do what you want:

import java.io.*;
import org.w3c.dom.*;

...
  public Element addElement(Document doc, Element el, String name, String value) {
      Element el1 = doc.createElement(name);
      if (el != null) el.appendChild(el1);
      else doc.appendChild(el1);
      if (value != null)  el1.appendChild(doc.createTextNode(value));
      return el1;
  }
...

        Document doc = new org.apache.xerces.dom.DocumentImpl();
        Element emp =  addElement(doc, null, "Employee", null);

        Element summary =  addElement(doc, emp, "summary", null);
        Element summary_rec =  addElement(doc, summary, "summary_record", null);
        summary_rec.setAttribute("tag", "12345");
        Element origin =  addElement(doc, summary_rec, "origin", null);
        addElement(doc, origin, "city", "KL");
        addElement(doc, origin, "country", "Malaysia");
        Element dest =  addElement(doc, summary_rec, "destination", null);
        addElement(doc, dest, "city", "SI");
        addElement(doc, dest, "country", "Singapore");
        Element status =  addElement(doc, summary_rec, "current_status", null);
        Element status_date =  addElement(doc, status, "last_event_date", null);
        addElement(doc, status_date, "month", "march");
        addElement(doc, status_date, "day", "12");
        addElement(doc, status_date, "year", "2002");
        Element status_time =  addElement(doc, status, "last_event_time", null);
        addElement(doc, status_time, "hours", "12");
        addElement(doc, status_time, "minutes", "30");

        addElement(doc, summary_rec, "nodatainfo", "success");

        Element hs_details =  addElement(doc, emp, "hs_details", null);

        org.apache.xml.serialize.XMLSerializer ss = new org.apache.xml.serialize.XMLSerializer();
        ByteArrayOutputStream doc_stream = new ByteArrayOutputStream();
        ss.setOutputByteStream(doc_stream);
        ss.serialize(doc);
        String doc_text = doc_stream.toString();
        System.out.println(doc_text);
0
 
Venci75Commented:
try this:

        URL url = new URL("http://google.yahoo.com/bin/query?p=java");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        int r;
        while ((r=is.read()) != -1)
            System.out.write(r);

this will return the Google search results for "java" .


You you want to first send data, before reading the response - you must use POST requests:

conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.getOutputStream.write("some data");


and then - read the response from the input stream
0
 
jason101799Author Commented:
Thanks Venci, what if my company is using a proxy server? Can u advice?

Thank you
Jason
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
jason101799Author Commented:
Venci,

The result shows only numbers. Can you explain?

Thanks
JAson
0
 
Venci75Commented:
There are system properties:
http.proxyPort
http.proxyHost
to set them at java startup - run java with the following parameters:
java -Dhttp.proxyPort=<port> -Dhttp.proxyHost=<host> ...

or set them at runtime with
System.setProperty("http.proxyHost", "proxy");
System.setProperty("http.proxyPort", "port");

0
 
jason101799Author Commented:
Venci,

I am getting the below error

-----------------------------------------------------------
, stack: java.lang.Exception: Java/JSP compile error: ../ClassCache/C1133537857/
caapps/cawebsrv/netscape/docs_dcs/jason/_nes_http.java:41: Method setProperty(ja
va.lang.String, java.lang.String) not found in class java.lang.System.          
 System.setProperty("http.proxyHost", "proxy.apis.dhl.com");                    
                   ^                                                            
../ClassCache/C1133537857/caapps/cawebsrv/netscape/docs_dcs/jason/_nes_http.java
:42: Method setProperty(java.lang.String, java.lang.String) not found in class j
ava.lang.System.                                                                
 System.setProperty("http.proxyPort", "8080");                                  
-----------------------------------------------------------

Please advice and how come the response back is in numerics only. How do I read the content?

Thanks once again

Jason

0
 
Venci75Commented:
The proxy properties must be set at the client side (not the server side)
0
 
Venci75Commented:
Are you using JSP at the server side?
0
 
jason101799Author Commented:
I am using JSP at the server side. ANyway why the response output is in integer? How can I read the actual content from the response.

Thanks
Jason
0
 
Venci75Commented:
you mean this:
int r; // THIS INTEGER
while ((r=is.read()) != -1)
   System.out.write(r);

to get it as String, use:
int len = conn.getContentLength();
byte[] b = new byte[len];
is.read(b);
String result=new String(b);
System.out.println(result);
 
0
 
jason101799Author Commented:
Venci,

Error occured when i place the codes out of the while loop. Btw where should place the above codes that you have mentioned.


-----------------------------------------------------------

[18/Apr/2002:17:05:50] failure (22008): Internal error: exception thrown from th
e servlet service function (uri=/jason/http.jsp): java.lang.NegativeArraySizeExc
eption, Stack: java.lang.NegativeArraySizeException                            
        at C1133537857.caapps.cawebsrv.netscape.docs_dcs.jason._nes_http.service
(Compiled Code)                                                                
        at javax.servlet.http.HttpServlet.service(Compiled Code)                
        at com.netscape.server.http.servlet.NSServletRunner.Service(Compiled Cod
----------------------------------------------------------
0
 
Venci75Commented:
sorry - forget my gat post. use this instead:
        URL url = new URL("http://google.yahoo.com/bin/query?p=java");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        int r;
        StringBuffer buff = new StringBuffer();
        while ((r=is.read()) != -1)
            buff.append((char)r);
        System.out.println(buff.toString());

buff.toString() contains the response as String
0
 
jason101799Author Commented:
Venci,

How come i get nothing out from the buffer?? i am actually using a local intranet url. Anyway when i tried this url ""http://google.yahoo.com/bin/query?p=java", error occured as below.

-----------------------------------------------------------
[18/Apr/2002:17:57:30] failure (22008): Internal error: exception thrown from th
e servlet service function (uri=/jason/http.jsp): java.net.NoRouteToHostExceptio
n: Connection timed out, Stack: java.net.NoRouteToHostException: Connection time
d out                                                                          
        at java.net.PlainSocketImpl.doConnect(Compiled Code)                    
        at java.net.PlainSocketImpl.connectToAddress(Compiled Code)            
        at java.net.PlainSocketImpl.connect(Compiled Code)                      
------------------------------------------------------

Please advice.


Thanks
Jason
0
 
Venci75Commented:
Aha - we shoud get back to the proxy problem.
I don't know why you got this error:
, stack: java.lang.Exception: Java/JSP compile error: ../ClassCache/C1133537857/
caapps/cawebsrv/netscape/docs_dcs/jason/_nes_http.java:41: Method setProperty(ja
va.lang.String, java.lang.String) not found in class java.lang.System.          
System.setProperty("http.proxyHost", "proxy.apis.dhl.com");                  

What is your java version?

I can suggest another way to do this, but I am not sure whether the result won't be the same:
        Properties p = System.getProperties();
        p.setProperty("http.proxyHost", "proxy");
        p.setProperty("http.proxyPort", "8080");
        System.setProperties(p);
        URL url = new URL("http://google.yahoo.com/bin/query?p=java");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        InputStream is = conn.getInputStream();
        int r;
        StringBuffer buff = new StringBuffer();
        while ((r=is.read()) != -1)
            buff.append((char)r);
        System.out.println(buff.toString());
        System.out.println("UsingProxy: " + conn.usingProxy());
0
 
jason101799Author Commented:
Ven,

Some error. Please advice. I am using JDK 1.18

-----------------------------------------------------------
../ClassCache/C1133537857/caapps/cawebsrv/netscape/docs_dcs/jason/_nes_http.java
:43: Method setProperty(java.lang.String, java.lang.String) not found in class j
ava.util.Properties.                                                            
 p.setProperty("http.proxyPort", "8080");                                      
              ^                                                                
Note: ../ClassCache/C1133537857/caapps/cawebsrv/netscape/docs_dcs/jason/_nes_htt
p.java uses a deprecated API.  Recompile with "-deprecation" for details.      
2 errors, 1 warning                                                            
                                                                               
        at com.netscape.server.http.jsp.JSPCompiler.compileJSP(Compiled Code)  
        at com.netscape.server.http.jsp.JSPCompiler.compileInstance(Compiled Cod
e)                                                                              
        at com.netscape.server.http.servlet.NSServletEntity.load(Compiled Code)
        at com.netscape.server.http.servlet.NSServletEntity.update(Compiled Code
)                                                                              
        at com.netscape.server.http.servlet.NSServletRunner.Service(Compiled Cod
e)                                                                              
                                                                               
-----------------------------------------------------------

Thanks
JAson
0
 
Venci75Commented:
aha - the Properties class in java 1 dosn't have setProperty method. Use this:

p.put("http.proxyPort", "8080");

instead of this:

p.setProperty("http.proxyPort", "8080");      


0
 
jason101799Author Commented:
Ven,

After I have set the properties and output the file, it was "Using proxy=false" . Please advice.

Cheers
Jason
0
 
Venci75Commented:
hmmm..
It semms that you have to configure these properties through the java start-up parameters. Can you check in the configuration of your web server whether you can supply parameters for the java machine. Because it seems that these parameters are ignored.
The java machive thould be started this way:
java -Dhttp.proxyPort=<port> -Dhttp.proxyHost=<host> ...

BTW: After you get
Using proxy=false
did you get the

java.net.NoRouteToHostException: Connection timed out, Stack: java.net.NoRouteToHostException:

error?
0
 
jason101799Author Commented:
Ven,

Yuppe, it still happens. Besides that I would like to know how can I read the information inside the buffer?? The buffer will contain all the information separated by carriage return? I would like to read the buffer information and manipulate the information inside. Please advice.

Thanks
Jason
0
 
Venci75Commented:
String result = buff.toString();
0
 
jason101799Author Commented:
Ven,

When you use buffered, the result will be a string value. So how can I manipulate the result to produce the desire output? The string will consist of something like that "A=1234B=3245C=908D=7625". If I need to separate the result, is there anyway I can do it?

Please advice.

Thanks
Jason
0
 
jason101799Author Commented:
Ven,

One more favor if you don't mind. How can I create an XML document using Java/JSP. I will increase the points.

Please help.


Thanks
Jason
0
 
Venci75Commented:
Regarding the XML:

you can use xerces ( http://xml.apache.org/xerces2-j/ )

this is an example code:

org.w3c.dom.Document doc = new org.apache.xerces.dom.DocumentImpl();
org.w3c.dom.Element el =  doc.createElement("Order");
el.setAttribute("test", "a&b");
org.w3c.dom.Element node = doc.createElement("Detail");
node.setAttribute("aa", "a&v");
el.appendChild(node);
node = doc.createElement("Detail");
node.setAttribute("aa", "as&");
el.appendChild(el);

org.apache.xml.serialize.XMLSerializer ss = new org.apache.xml.serialize.XMLSerializer();


ss.setOutputByteStream(System.out);
ss.serialize(doc);



If you want to get the XML as String, you can do this (replace the last two lines with the following):


java.io.ByteArrayOutputStream doc_stream = new java.io.ByteArrayOutputStream();
ss.setOutputByteStream(doc_stream);
ss.serialize(doc);
String doc_text = doc_stream.toString();



Regarding the result parsing:
I have a question regarding the format of this:
"A=1234B=3245C=908D=7625"
Am I correct that you have something like this:
<name>=<value><name>=<value>...
where values are numbers
0
 
jason101799Author Commented:
Ven,

Yes, it's more like key value pair. Sorry for asking too  much but I have an xml structure listed below and I would be grateful if you can help me with the source.

----------------------------------------------------------
<Employee>
 <summary>
  <summary_record tag="12345">
   <origin>
    <city>KL</city>
    <country>Malaysia</country>
   </origin>
   <destination>
    <city>SI</city>
    <country>Singapore</country>
   </destination>
   <current_status>
    <last_event_date>
     <month>march</month>
     <day>12</day>
     <year>2002</year>
    </last_event_date>
    <last_event_time>
     <hours>12</hours>
     <minutes>30</minutes>
    </last_event_time>
   </current_status>
   <nodatainfo>success</nodatainfo>
  </summary_record>
 </summary>
 <hs_details>
  <event_record tag="1234">
  <service_events>
   <event_date>
    <month>April</month>
    <day>12</day>
    <year>2002</year>
   </event_date>
   <event_time>
    <hours>12</hours>
    <minutes>20</minutes>
   </event_time>
   <event_station>
    <city>KL</city>
    <country>Malaysia</country>
   </event_station>
   <event_comments>Good</event_station>
  </service_events>
  (...<service_events>.....</service_events>) <--this will increase based on the data received.
  </event_record>
 </hs_details>
</employee>

-----------------------------------------------------------

I hope that is not too much of a trouble. Thank you once again.

Cheers
Jason
 
0
 
jason101799Author Commented:
Ven,

I almost forgot, I need to output it to a physical xml file. Let says I have a vector that stores all my key value pair in the vector, how can I split the vector element to get the data and place it in the xml file.

Thank You.

Cheers
Jason
0
 
jason101799Author Commented:
Ven,

When I tried System.out.println, there was nuthing printed. Which part has gone wrong? I did not see any errors as well. The codes were copied from the reply before this. Can you advice?

Thanks
JAson
0
 
Venci75Commented:
can you post your code
0
 
jason101799Author Commented:
Ven,

Error encountered. Please help.

-----------------------------------------------------------

org.w3c.dom.DOMException: DOM006 Hierarchy request error                      
        at org.apache.xerces.dom.ParentNode.internalInsertBefore(Compiled Code)
        at                                                                    
        at                                                                    
        at BuildXML1.main(BuildXML1.java:25)                                  
---------------------------------------------------------

Thanks mate

Jason
0
 
Venci75Commented:
post your code - so I will be able to find the problem
0
 
jason101799Author Commented:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.Serializer;
import org.apache.xml.serialize.SerializerFactory;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.BaseMarkupSerializer;
import org.apache.xerces.dom.DocumentImpl;
import java.io.*;
public class BuildXML1{                                                           public static void main(String argv[]){                                                             try
    {          
     org.w3c.dom.Document doc = new org.apache.xerces.dom.DocumentImpl();
     org.w3c.dom.Element el = doc.createElement("Order");
     el.setAttribute("test","123");
     org.w3c.dom.Element node = doc.createElement("Detail");
     node.setAttribute("aa", "a&v");
     el.appendChild(node);
     node = doc.createElement("Detail");
     node.setAttribute("aa", "as&");
     el.appendChild(el);
     org.apache.xml.serialize.XMLSerializer serial = new org.apache.xml.serializ
e.XMLSerializer();
     ByteArrayOutputStream doc_stream = new ByteArrayOutputStream();
     serial.setOutputByteStream(doc_stream);
     serial.serialize(doc);
     String doc_text = doc_stream.toString();
     System.out.println("test="+doc_text);
     } catch (Exception e)
     {
       e.printStackTrace();
     }
  }
}


-----------------------------------------------------------

I have attached the codes for your perusal. Please advice.


Cheers
Jason
0
 
Venci75Commented:
there is a line
el.appendChild(el);

replace it with
el.appendChild(node);

0
 
jason101799Author Commented:
Ven,

Nothing come out. Anyway how can I write to a file? Can u advice?

Thanks
Jason

0
 
Venci75Commented:

org.w3c.dom.Document doc = new org.apache.xerces.dom.DocumentImpl();
org.w3c.dom.Element el = doc.createElement("Order");
doc.appendChild(el); // add this line
...


to save the XML to a file use this:
    FileOutputStream doc_stream = new FileOutputStream("c:/my_doc.xml");
    serial.setOutputByteStream(doc_stream);
    serial.serialize(doc);
    doc_stream.flush();doc_stream.close();
     
instead of this:
    ByteArrayOutputStream doc_stream = new ByteArrayOutputStream();
    serial.setOutputByteStream(doc_stream);
    serial.serialize(doc);
    String doc_text = doc_stream.toString();
    System.out.println("test="+doc_text);
   
0
 
jason101799Author Commented:
Ven,

I still face error. Below as attach:

-----------------------------------------------------------
org.w3c.dom.DOMException: DOM006 Hierarchy request error                      
        at org.apache.xerces.dom.ParentNode.internalInsertBefore(Compiled Code)
        at org.apache.xerces.dom.ParentNode.insertBefore(Unknown Source)      
        at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)          
        at BuildXML1.main(BuildXML1.java:19)                                  
-----------------------------------------------------------

Please advice.

Cheers
Jason
0
 
jason101799Author Commented:
Ven,
I have got in working and I know which part went wrong. I have a qs, how do I set the indent and line separator?
0
 
Venci75Commented:
It is complicated. You must to extend the XMLSerializer class in order to do that. I tried it once but it wasn't very successful.
0
 
jason101799Author Commented:
Ven,

What abt the error I faced? Please advice.

Thanks
Jason
0
 
Venci75Commented:
post the latest code
0
 
jason101799Author Commented:
Ven,

I have tried your new codes with the function u provided earlier. I am facing a new problem. Attach as below.

----------------------------------------------------------
BuildXML1.java:42: Can't make static reference to method org.w3c.dom.Element add
Element(org.w3c.dom.Document, org.w3c.dom.Element, java.lang.String, java.lang.S
tring) in class BuildXML1.                                                      
     Element summary =  addElement(doc, root, "SUMMARY", null);                
                                  ^                                            
BuildXML1.java:43: Can't make static reference to method org.w3c.dom.Element add
Element(org.w3c.dom.Document, org.w3c.dom.Element, java.lang.String, java.lang.S
-----------------------------------------------------------

Please advice.

Thanks
Jason
0
 
Venci75Commented:
because you are calling this method from the main() method - you need to declare it as static:
public static Element addElement(Document doc, Element el, String name, String value) {
...
     
0
 
jason101799Author Commented:
Ven,

I have attach the codes for you to advice. I am facing errors.


Codes in JSP
-----------------------------------------------------------
<%@ page language="java" %>                                                    
<%@ page import="java.lang.*,java.io.*,java.util.*,java.net.*" %>              
<%@ page import="org.w3c.dom.*"; %>                                            
<%@ page import="javax.xml.parsers.*"; %>                                      
<%@ page import="org.apache.xml.serialize.OutputFormat"; %>                    
<%@ page import="org.apache.xml.serialize.Serializer"; %>                      
<%@ page import="org.apache.xml.serialize.SerializerFactory"; %>                
<%@ page import="org.apache.xml.serialize.XMLSerializer"; %>                    
<%@ page import="org.apache.xml.serialize.BaseMarkupSerializer"; %>            
<%@ page import="org.apache.xerces.dom.DocumentImpl"; %>                        
                                                                               
<%! public Element addElement(Document doc, Element el, String name, String valu
e)                                                                              
    {                                                                          
      Element el1 = doc.createElement(name);                                    
      if(el != null)                                                            
      {                                                                        
        el.appendChild(el1);                                                    
      }                                                                        
      else                                                                      
      {                                                                        
        doc.appendChild(el1);                                                  
      }                                                                                                                                    
      if(value != null)                                                        
      {                                                                        
        el1.appendChild(doc.createTextNode(value));                            
      }                                                                        
                                                                               
     return el1;                                                                
    }                                                                          
%>                                                                              
<%                                                                              
try                                                                            
{                                                                              
 org.w3c.dom.Document doc = new org.apache.xerces.dom.DocumentImpl();          
 Element root = addElement(doc, null, "TRACK", null);                          
 Element summary = addElement(doc, root, "SUMMARY", null);                      
 OutputFormat format = new OutputFormat(doc);                                  
 format.setLineSeparator("\n");                                                
 format.setIndenting(true);                                                    
 StringWriter stringOut = new StringWriter();                                  
 org.apache.xml.serialize.XMLSerializer serial = new org.apache.xml.serialize.XM
LSerializer(stringOut,format);                                                  
 FileOutputStream doc_stream = new FileOutputStream("my_doc.xml");              
 serial.setOutputByteStream(doc_stream);                                        
 serial.serialize(doc);    
 doc_stream.flush();        
 doc_stream.close();        
} catch (Exception e)      
{                          
 e.printStackTrace();      
}                          
%>                          
                     










-----------------------------------------------------------


Error Description
-----------------------------------------------------------
[23/Apr/2002:11:33:07] failure (22008): Internal error: exception thrown from th
e servlet service function (uri=/jason/generateXml.jsp): java.lang.NoSuchMethodE
rror: org.w3c.dom.Node: method getLocalName()Ljava/lang/String; not found, Stack
: java.lang.NoSuchMethodError: org.w3c.dom.Node: method getLocalName()Ljava/lang
/String; not found                                                              
        at org.apache.xml.serialize.XMLSerializer.serializeElement(Compiled Code
)                                                                              
        at org.apache.xml.serialize.BaseMarkupSerializer.serializeNode(Compiled
Code)                                                                          
        at org.apache.xml.serialize.BaseMarkupSerializer.serializeNode(Compiled
Code)                                                                          
        at org.apache.xml.serialize.BaseMarkupSerializer.serialize(Compiled Code
)                                                                              
        at C2077059941.caapps.cawebsrv.netscape.docs_dcs.jason._nes_generateXml.
service(_nes_generateXml.java:89)                                              
        at javax.servlet.http.HttpServlet.service(Compiled Code)                
        at com.netscape.server.http.servlet.NSServletRunner.Service(Compiled Cod
e)                                                                              
-----------------------------------------------------------
0
 
Venci75Commented:
It seems you have mixed the versions of xerces on your server. Check whether there are no other versions of XML parsers there
0
 
jason101799Author Commented:
Ven,

If i have a string of Japanese language, how can I output the japanese language into an xml format?? The basic serialize doesn't seem to work. Can u advice.


Thanks
Jason
0
 
Venci75Commented:
You can use this:

org.w3c.dom.Document doc = new org.apache.xerces.dom.DocumentImpl();
doc.setEncoding("UTF-8");

This way the your XML document will be in unicode
0
 
jason101799Author Commented:
Ven,

If I need to return my xml in other languages?? I need your advice about validating xml schema using JAXP parser. I will be grateful if you can help. Currently I have a sets of codes that read the xml into a http request but I did not validate the xml against any dtd or schema.

Thanks
Jason
0
 
jason101799Author Commented:
Ven,

Another problem that I faced and I need your advice. If the data inside and element consists of "'", how come it was translated to "&apos;".

BTW, the doc.setEncoding returns error and I have attach the error log here.

-----------------------------------------------------------
1 error, 1 warning                                                              
, stack: java.lang.Exception: Java/JSP compile error: ../ClassCache/C2077087319/
caapps/cawebsrv/netscape/docs_dcs/track/_nes_generateXml.java:165: Method setEnc
oding(java.lang.String) not found in interface org.w3c.dom.Document.            
   doc.setEncoding("EU_KOR");                                                  
-----------------------------------------------------------

Thanks.
Jason
0
 
jason101799Author Commented:
Ven,

Any luck on the problem mentioned above? Hear from you soon.

Cheers mate
0
 
jason101799Author Commented:
Thanks venci75, it was excellent
0
 
jason101799Author Commented:
Venci75,

I need to send a request as XML using Httprequest and get a response as XML as well. Then the program who initiated the HttpRequest should read the XML and extract the data from the response message.

If you can provide me samples of codes, I will open it as a new qs.

Your help will be grateful.

Many thanks
Jason
0
All Courses

From novice to tech pro — start learning today.