httpUrlConnection

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
sklimAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
CEHJConnect With a Mentor Commented:
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
 
CEHJCommented:
Well there's no code to read the response there that i can see ...
0
 
TimYatesCommented:
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
tapasviCommented:

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
 
TimYatesCommented:
> The right link is :

Whoops ;-)  Ta :-D
0
 
CEHJCommented:
>>following is a sketchy implementation,,,

The servlets are on different servers
0
 
tapasviCommented:
well, then we always have perennially favourite request dispatcher forward(req, resp)  
0
 
rrzCommented:
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
 
sklimAuthor Commented:
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
 
CEHJCommented:
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
 
sklimAuthor Commented:
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
 
CEHJCommented:
OK that all sounds OK, but you need to post more code, particularly around how servletB is getting invoked
0
 
sklimAuthor Commented:
hi CEHJ, the code posted above is what servletB will do.

the codes in the question is what ServletA does.

0
 
sklimAuthor Commented:
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
 
CEHJCommented:
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
 
CEHJCommented:
1) That may need encoding, depending on what's sent
0
 
sklimAuthor Commented:
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
 
CEHJCommented:
>>
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
 
sklimAuthor Commented:
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
 
sklimAuthor Commented:
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
 
CEHJCommented:
>>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
 
sklimAuthor Commented:
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
 
sklimAuthor Commented:
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
 
CEHJCommented:
You need to be implementing doPost in your servlet
0
 
TimYatesCommented:
fair enough :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.