M.S.Naidu
M.S.Naidu

Reputation: 2289

HttpUrlConnection redirection to other servlet is not happening

I have the following code which will call the server through HttpUrlConnection.

String response = HttpUtil.submitRequest(json.toJSONString(), "http://ipaddr:port/SessionMgr/validateSession?sessionId=_78998348uthjae3a&showLoginPage=true");

The above lines will call the following code:

public static String submitRequest(String request, String **requestUrl**) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStream os = conn.getOutputStream();
        os.write(request.getBytes());
        os.flush();
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        StringBuffer sb = new StringBuffer();
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        conn.disconnect();
        return sb.toString();

    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
    return "";
}

The requestUrl will go to the servlet below:

public class ValidateSessionServlet extends HttpServlet {
    String session = req.getParameter(sessionId);
    if (session == null) {
    // redirect to servlet which will display login page.
    response.setContentType("text/html");
            String actionUrl = getIpPortUrl(request)
                            + PropertyConfig.getInstance().getFromIdPConfig(globalStrings.getCheckSSOSession());
            out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> \n");
            out.write("<html><head><body onload=\"document.forms[0].submit()\">\n");
            out.write("<form method=\"POST\" action=\"" + actionUrl + "\">\n");
            out.write("<input type=\"hidden\" name=\"locale\" value=\"" + locale + "\"/>\n");
            out.write("<input type=\"hidden\" name=\"Sessionrequest\" value=\"" + true + "\"/>\n");
            out.write("</form>\n</body>\n</html>\n");
     }
}

In the above code the form should go to the servlet as mentioned in the actionUrl, but it is again going to servlet which is in step(1).

1) May i know can we make this above html form in step(3) to submitted and redirect to the servlet in actionUrl.

As per the above code i am summarizing the requirement. If the session is null, I have to redirect the user to login page and validated against database and then the response should go to step(1), Is it possible?

Upvotes: 4

Views: 1542

Answers (2)

sun
sun

Reputation: 290

To clarify, setInstanceFollowRedirects(true) only dictates whether HTTP redirects should be automatically followed by the HttpURLConnection instance. In your particular case, it seems that you want to redirect to servlets based on whether session is null (or some other condition based on your specific application logic).

The correct (and more bug-proof solution) is to check for HTTP 3xx status code cases and manually handle the redirect. Here is a code snippet as an example:

if (responseStatusCode != HttpURLConnection.HTTP_OK) {
   switch(responseStatusCode){ 
      case HttpURLConnection.HTTP_MOVED_TEMP:
          // handle 302
      case HttpURLConnection.HTTP_MOVED_PERM:
          // handle 301
      case HttpURLConnection.HTTP_SEE_OTHER:                        
          String newUrl = conn.getHeaderField("Location");   // use redirect url from "Location" header field
          String cookies = conn.getHeaderField("Set-Cookie");       // if cookies are needed (i.e. for login)
          // manually redirect using a new connection 
          conn = (HttpURLConnection) new URL(newUrl).openConnection();
          conn.setRequestProperty("Cookie", cookies);
          conn.addRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1"); 
      default:
          // handle default (other) case
   }
}

The above code is similar to what I use for my app's user login redirects, and I've found that it's very easy to debug. (In general, I handle HTTP status code cases manually in order to avoid bugs down the road.)

Finally, I would recommend using a good JSON lib, such as json.org, to parse your responses.

Upvotes: 2

SilentKnight
SilentKnight

Reputation: 14021

If you want your HttpUrlConnection to support redirections, you need to set your HttpUrlConnection like this:

...
conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
conn.setInstanceFollowRedirects(true);
...

Then if your server redirect your request somewhere else, conn will receiver the redirected response.

Upvotes: 3

Related Questions