Announcement Announcement Module
Collapse
No announcement yet.
spring security -- HttpURLConnection Page Title Module
Move Remove Collapse
This topic is closed
X
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • spring security -- HttpURLConnection

    Hi,
    I am having a URL which is authenticated and authorized using spring-security . It is working fine when the user is logging in usign a browser.
    How do I submit a request to that URL using another java program running on different jvm making a connection using HttpURLConnection .

    Thanks,
    Alok.

  • #2
    you can use this class as you like
    Code:
    HttpClient client = new HttpClient();
    client.sendMessageToEndPoint(url, "<message>hello world</message>");
    Code:
    public final class HttpClient implements Serializable {
    
        /** Unique Id for serialization. */
        private static final long serialVersionUID = -5306738686476129516L;
    
        /** The default status codes we accept. */
        private static final int[] DEFAULT_ACCEPTABLE_CODES = new int[] {
            HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_MODIFIED,
            HttpURLConnection.HTTP_MOVED_TEMP, HttpURLConnection.HTTP_MOVED_PERM,
            HttpURLConnection.HTTP_ACCEPTED};
    
        private Log log = LogFactory.getLog(this.getClass());
    
        /** List of HTTP status codes considered valid by this AuthenticationHandler. */
    
        private int[] acceptableCodes = DEFAULT_ACCEPTABLE_CODES;
    
        private int connectionTimeout = 5000;
    
    
        private int readTimeout = 5000;
        
        private String sessionId = null;
        
        public boolean sendMessageToEndPoint(final String url, final String message) {
            HttpURLConnection connection = null;
            try {
            	
            	String urlId;
            	if ( sessionId == null ) {
            		urlId = url;
            	}else{
            		urlId = url + ";jsessionid=" + sessionId;
            	}        	
            	
                final URL logoutUrl = new URL(urlId);
                final String output = "message=" + URLEncoder.encode(message, "UTF-8");
    
                connection = (HttpURLConnection) logoutUrl.openConnection();
    
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setReadTimeout(this.readTimeout);
                connection.setConnectTimeout(this.connectionTimeout);
                connection.setRequestProperty("Content-Length", ""
                    + Integer.toString(output.getBytes().length));
                connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
                final DataOutputStream printout = new DataOutputStream(connection
                    .getOutputStream());
                printout.writeBytes(output);
                printout.flush();
                printout.close();
    
                final BufferedReader in = new BufferedReader(new InputStreamReader(connection
                    .getInputStream()));
    
                while (in.readLine() != null) {
                    // nothing to do
                }
                
                sessionId = connection.getHeaderField("url-attmt");
                
                return true;
            } catch (final Exception e) {
                return false;
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    
        public boolean isValidEndPoint(final String url) {
            try {
                final URL u = new URL(url);
                return isValidEndPoint(u);
            } catch (final MalformedURLException e) {
                return false;
            }
        }
    
        public boolean isValidEndPoint(final URL url) {
            HttpURLConnection connection = null;
            try {
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(this.connectionTimeout);
                connection.setReadTimeout(this.readTimeout);
    
                connection.connect();
    
                final int responseCode = connection.getResponseCode();
    
                for (int i = 0; i < this.acceptableCodes.length; i++) {
                    if (responseCode == this.acceptableCodes[i]) {
                        if (log.isDebugEnabled()) {
                            log.debug("Response code from server matched "
                                + responseCode + ".");
                        }
                        return true;
                    }
                }
    
                if (log.isDebugEnabled()) {
                    log
                        .debug("Response Code did not match any of the acceptable response codes.  Code returned was "
                            + responseCode);
                }
            } catch (final IOException e) {
                log.error(e,e);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return false;
        }
    
        /**
         * Set the acceptable HTTP status codes that we will use to determine if the
         * response from the URL was correct.
         * 
         * @param acceptableCodes an array of status code integers.
         */
        public final void setAcceptableCodes(final int[] acceptableCodes) {
            this.acceptableCodes = acceptableCodes;
        }
    
        public void setConnectionTimeout(final int connectionTimeout) {
            this.connectionTimeout = connectionTimeout;
        }
    
        public void setReadTimeout(final int readTimeout) {
            this.readTimeout = readTimeout;
        }
    }

    Comment


    • #3
      Hi,
      The url to which the client has to make a connection is a Secured url on the server , protected by form based authentication ( As it is possible to access the same url from the browser by a customer ) .
      So in the code that you have pasted, there is no authentication parameters ...how can this work....


      Thanks,
      Alok.

      Comment

      Working...
      X