Solved

httpUrlConnection

Posted on 2004-07-30
27
1,439 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
  • 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
 
LVL 13

Expert Comment

by:Webstorm
ID: 11677502
0
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 
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 27

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 125 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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Java Server Faces parameter pass? 6 50
Java SE 8u111  Lot of stuff broke 11 69
iterator/ListIterator approach 17 27
Desingning Refactoring existing code 2 24
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

803 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