?
Solved

httpUrlConnection

Posted on 2004-07-30
27
Medium Priority
?
1,454 Views
Last Modified: 2012-06-27
Hi

I need to build a servlet that response to a server's request. I'm using HttpURLConnection. Basically the scenario is ServerA request some info from ServerB. When ServerB receive the request, ServerB will give feedback to ServerA. Everything is done backend (without using browser)

During the testing, i built 2 servelts, one requestorA and one responderB. however, the requestorA can never recieve the response from responderB.

below is the code that i use

URL url = null;
HttpURLConnection connection = null;

url = new URL("http://localhost:9080/updateServlet");

connection = (HttpURLConnection) url.openConnection();
connection.setDoInput (true);
connection.setDoOutput (true);
connection.setUseCaches (false);
connection.setRequestMethod("POST");
connection.setRequestProperty("field1", "111");
connection.connect();

Question:
1) am i doing the right thing?
2) why can't i get any response? what is the right way to do?

Thanks
0
Comment
Question by:sklim
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 9
  • 3
  • +3
27 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11676952
Well there's no code to read the response there that i can see ...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11676957
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Expert Comment

by:tapasvi
ID: 11677517

well , you dont need to use URLConnection  for inter servlet communication

following is a sketchy implementation,,,

ServletContext context = getServletContext();
Servlet servlet = context.getServlet(name);
Method doP = servlet.getClass().getMethod("doPost", new Class[]{"111".getClass()});
doP.invoke(servlet, {"111"});

0
 
LVL 35

Expert Comment

by:TimYates
ID: 11677525
> The right link is :

Whoops ;-)  Ta :-D
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11677567
>>following is a sketchy implementation,,,

The servlets are on different servers
0
 
LVL 4

Expert Comment

by:tapasvi
ID: 11677661
well, then we always have perennially favourite request dispatcher forward(req, resp)  
0
 
LVL 28

Expert Comment

by:rrz
ID: 11682673
Cut and paste these two pages to test.



-----------------------------------------requestorA.jsp-------------------------------------
<%@ page import="java.util.*,java.net.*,java.io.*" %>
<%          
  Vector vSend = new Vector();        
  vSend.add("one");        
  vSend.add("two");      
  vSend.add("three");        
  URL url = new URL(http://localhost:9080/responderB.jsp");  //  change url ?    
  HttpURLConnection conn = (HttpURLConnection)url.openConnection();      
  conn.setDoOutput(true);        
  conn.setDoInput(true);        
  conn.setRequestMethod("POST");        
  conn.setRequestProperty("Content-type", "application/octet-stream");        
  ObjectOutputStream oos = new ObjectOutputStream(conn.getOutputStream());      
  oos.writeObject(vSend);        
  oos.flush();      
  ObjectInputStream in = new ObjectInputStream(conn.getInputStream());        
  Vector vBack = (Vector)in.readObject();      
  in.close();      
  oos.close();%>vBack=<%=vBack%>

------------------------------------------responderB.jsp-----------------
<%@ page import="java.net.*,java.io.*" %>
<%      
  ObjectInputStream ois = new ObjectInputStream(request.getInputStream());      
  ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());      
  oos.writeObject(ois.readObject());        
  oos.flush();        
  ois.close();        
  oos.close();
%>
0
 

Author Comment

by:sklim
ID: 11683005
yes, CEHJ is correct. the servlets are on 2 different server. and these are done without browser (backend)... it's server to server program, transparent to user.

well, the servlet that read the response actually consists of doGet and doPost methods. just trying to see if it manage to receive the response from responderB. but i never get anything.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683501
Please post the code you're actually using. The code you posted above never tries to read anything, so you can't hope to get a response ...
0
 

Author Comment

by:sklim
ID: 11683517
ok. let me explain more...

say i send a GET request using
http://serverA:9080/ServletA?parameter1=abc¶meter2=123

in  ServletA, it's supposed to lookup the database to get the status.
Then it will update serverB
http://serverB:9080/ServletB?parameter1=abc¶meter2=123&status=OK

ServletB, receive the status and process.

the code that reads the response...

protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
super.doGet(arg0, arg1);
System.out.println("in test servlet");
System.out.println(arg0.getParameter("parameter1"));
}

I've duplicate the same thing for doPost method... just to prove that it receive the response. But i never get anything.


Actually, i've tried using http://localhost:9080/updateServlet?parameter1=abc too... still not getting anything from HttpUrlConnection


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683566
OK that all sounds OK, but you need to post more code, particularly around how servletB is getting invoked
0
 

Author Comment

by:sklim
ID: 11683608
hi CEHJ, the code posted above is what servletB will do.

the codes in the question is what ServletA does.

0
 

Author Comment

by:sklim
ID: 11683638
hm... am i doing the right thing?

1) should i set the parameter as query string and concate with the url?
URL url = new URL(http://localhost:9080/responderB.jsp?parameter1=abc");

2) does "HttpURLConnection conn = (HttpURLConnection)url.openConnection();" means the request is sent?

3) do i need "connection.connect();" to open the connection?

4) by right the receiver (ServletB) will be able to get the response, right? from doGet() method?

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683651
1) Yes
2) Yes
3) No i don't think so
4) You don't have to do setOutput, simply read the response from servlet B
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683656
1) That may need encoding, depending on what's sent
0
 

Author Comment

by:sklim
ID: 11683659
you mean from doGet() in servletB i'm able to receive the response, right?

as you can see from the codes i posted, i only try to print out some message to indicate that servlet B does receive the message, but i never see such message.

Any idea what causes it?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683688
>>
but i never see such message.

Any idea what causes it?
>>

Well, as i keep saying, so far i've seen no evidence of code trying to read the response
0
 

Author Comment

by:sklim
ID: 11683793
uh... do u mean i've successfully sent the request (from ServletA), but my servletB is not correct?

then how should my ServletB read the response?

can you please provide an example?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 375 total points
ID: 11683807
Really the situation is equivalent to the following, which you can run:

import java.net.*;
import java.io.*;

public class Yahoo {

      public static void main(String[] args) throws Exception {
            InputStream is = getResponse();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String buffer = null;
            while ((buffer = in.readLine()) != null) {
                  System.out.println(buffer);
            }
            in.close();

      }

      static InputStream getResponse() throws Exception {
                  URL url = new URL("http://search.yahoo.com/search");
                  HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                  conn.setRequestMethod("POST");
                  conn.setDoOutput(true);
                  conn.setDoInput(true);
                  conn.setRequestProperty("ContentType", "application/x-www-form-urlencoded");
                  conn.connect();
                  PrintStream ps = new PrintStream(conn.getOutputStream());
                  ps.print("p");
                  ps.print("=");
                  ps.print(URLEncoder.encode("java examples"));
                  ps.flush();
                  ps.close();
                  return conn.getInputStream();
       }

}
0
 

Author Comment

by:sklim
ID: 11683903
sorry, i think there are some misunderstanding

See, actually i need to know how "http://search.yahoo.com/search" response to the request (how does it send back the results to your Yahoo class).

in your case, A send request to B, then get result. but what will B need to do in order to send back the result to A?

must it be done using Application? i need to make it as an web services. Thought servlet will serve the purpose.

So if i'm building a servlet, why can't doGet method get the result?

Thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683933
>>then get result. but what will B need to do in order to send back the result to A?

Yes, when you get the result you need to get A to *read* it. All B needs to do is to send the result by writing it in doPost. In my example, main (A) is reading the result, the Yahoo 'servlet' (B) is sending it
0
 

Author Comment

by:sklim
ID: 11690763
Hi CEHJ

if i follow your example, i get the following error when i get the PrintStream

java.net.ProtocolException: Can't reset method: already connected


Anyway, i still can't get anything from the doGet (or doPost) method...

why don't u try to put the codes in the way that i need it? (if you can make it work, i can double the points for u :) )


*******************************************
Servlet A {
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
 // get request, send the results to servlet B (in different server)
}
}

Servlet B {
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
 // get request from Servlet A and process
}  
}

Servlet A will be triggered by sending in a request to Servlet A e.g.
http://ServerA:9080/ServletA?parameter1=abc

Thanks
0
 

Author Comment

by:sklim
ID: 11690819
ok. one more thing, when i try send request, i keep getting this error

"Error 405: HTTP method GET is not supported by this URL"

is it why i can't get anything from my Servlet B? what's wrong with my servlets?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11692874
You need to be implementing doPost in your servlet
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11880079
fair enough :-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month8 days, 9 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question