Java URL Value Check invokeUrl(String url)

Here you can find the source of invokeUrl(String url)

Description

This is a generic method to invoke the REST API.

License

Open Source License

Parameter

Parameter Description
url represents a signed request with "Signature" param

Exception

Parameter Description

Return

String representing the outcome of the REST API call

Declaration

public static String invokeUrl(String url) throws IOException 

Method Source Code

//package com.java2s;
/**/*ww  w. ja  va  2 s  . co m*/
 * Copyright 2007-2016, Kaazing Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    /**
     * This is a generic method to invoke the REST API. The URL that is passed
     * in should result in a signed request with the "Signature" query parameter
     * included. It's the caller's responsibility to deal with the return value
     * which may be a simple string or a XML response.
     *
     * @param url           represents a signed request with "Signature" param
     * @return String       representing the outcome of the REST API call
     * @throws java.io.IOException  is thrown if the connection times out or the query
     *                      params are incorrectly specified
     */
    public static String invokeUrl(String url) throws IOException {
        if (url == null) {
            throw new IllegalArgumentException("Null parameter passed in");
        }

        URL urlObj;
        InputStream inStream = null;
        String response = null;
        HttpURLConnection connection = null;

        try {
            // Create the HttpURLConnection.
            urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();

            // Only need HTTP GET.
            connection.setRequestMethod("GET");

            // Set 2seconds timeout interval.
            connection.setConnectTimeout(2 * 1000);
            connection.setReadTimeout(2 * 1000);

            connection.connect();

            // Read the output from the server.

            try {
                inStream = connection.getInputStream();
                // System.out.println("Return Code: " + connection.getResponseCode());
            } catch (IOException ex) {
                // Check the error stream for additional information that can
                // be useful to address the issue. If there is nothing in the
                // response body, HttpURLConnection.getErrorStream() returns a
                // null.
                inStream = connection.getErrorStream();
                if (inStream == null) {
                    // If connection.getErrorStream() is null, just use the
                    // message from the exception.
                    response = ex.getMessage();
                } else {
                    // Otherwise, get the error stream content and use it as
                    // a message for the new IOException instance that wraps the
                    // original IOException instance.
                    response = getResponse(inStream);
                    inStream.close();
                    inStream = null; // To deal with the check in finally.
                }

                throw new IOException(url + "\n" + response, ex);
            }

            response = getResponse(inStream);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException ioe) {
                    // Swallow this exception.
                }
            }

            if (connection != null) {
                connection.disconnect();
            }
        }

        return response;
    }

    private static String getResponse(InputStream in) {
        if (in == null) {
            return null;
        }

        InputStreamReader inReader = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(inReader);
        StringBuilder strBuilder = new StringBuilder();

        try {
            String line;
            while ((line = reader.readLine()) != null) {
                strBuilder.append(line + "\n");
            }
        } catch (Exception ex) {
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    // Swallow this exception.
                }
            }
        }

        String response = (strBuilder.length() > 0) ? strBuilder.toString()
                : null;
        return response;
    }
}

Related

  1. checkURLAvailable(String targetUrl)
  2. checkUrlImage(final String url)
  3. checkURLStatus(String pURL)
  4. checkURLValidProtocol(URL url)
  5. invokePostUrl(String url, String encodedQueryString)
  6. is200(final String url)
  7. is404(URL url)
  8. isAddressReachable(String url, int timeout)
  9. isAValidURL(String url)