0

HI,

Can we make the POST call from one server to another web server. For example, one web application deployed in server1. When we call the web application deployed in the server2, can we call using the POST method type. or always it can be GET method with explicit URLs

jackJoe
  • 10,664
  • 8
  • 45
  • 62
Krishna
  • 6,706
  • 15
  • 64
  • 79

2 Answers2

3

Two ways:

  1. If your current request is already POST, just send a 307 redirect.

    response.setStatus(307);
    response.setHeader("Location", "http://other.com");
    

    This will however issue a security confirmation warning at the client side.

  2. Play for proxy yourself.

    URLConnection connection = new URL("http://other.com").openConnection();
    connection.setDoOutput(true); // POST
    // Copy headers if necessary.
    
    InputStream input1 = request.getInputStream();
    OutputStream output1 = connection.getOutputStream();
    // Copy request body from input1 to output1.
    
    InputStream input2 = connection.getInputStream();
    OutputStream output2 = response.getOutputStream();
    // Copy response body from input2 to output2.
    

    This will however not change the URL and the client thinks he's still on your site.

See also:


Update: you actually wanted to redirect from POST to GET including all request parameters. In this case, just collect the POST parameters and send them along as query string in a default (302) redirect.

String encoding = request.getCharacterEncoding();
if (encoding == null) {
    encoding = "UTF-8";
    request.setCharacterEncoding(encoding);
}
StringBuilder query = new StringBuilder();

for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
    for (String value : entry.getValue()) {
        if (query.length() > 0) query.append("&");
        query.append(URLEncoder.encode(entry.getKey(), encoding));
        query.append("=");
        query.append(URLEncoder.encode(value, encoding));
    }
}

response.sendRedirect("http://example.com?" + query);
Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
2

Yes you can using HTTPURLConnection

here is example

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
//log it ,sms it, mail it
}
jmj
  • 225,392
  • 41
  • 383
  • 426