Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java

public static LocationInfo getLocationInfo(Location location) throws CantGetWeatherException {
    LocationInfo li = new LocationInfo();

    // first=tagname (admin1, locality3) second=woeid

    HttpURLConnection connection = null;
    try {//from  w  w  w .j a  va  2 s .  c o m
        connection = Utils.openUrlConnection(buildPlaceSearchUrl(location));

        InputStream inputStream = connection.getInputStream();
        return parseLocationInfo(li, inputStream);

    } catch (IOException | XmlPullParserException e) {
        throw new CantGetWeatherException(true, R.string.no_weather_data, "Error parsing place search XML", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.bloomreach.bstore.highavailability.utils.SolrInteractionUtils.java

/**
 * Execute a Http Command with a given read Timeout
 *
 * @param timeout//from   w  w  w.  j  a va  2  s  .  co  m
 * @param command
 * @return {@link java.io.InputStream} of the obtained response
 * @throws IOException
 */
public static InputStream executeSolrCommandAndGetInputStreamWithTimeout(int timeout, String command)
        throws IOException {
    //logger.info("Command to Execute: " + command);
    URL obj = new URL(command);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setConnectTimeout(timeout); //set timeout to 30 seconds
    con.setReadTimeout(timeout); //set timeout to 30 seconds
    return con.getInputStream();
}

From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java

public static CircularArray<LocationSearchResult> findLocationsAutocomplete(String startsWith) {
    CircularArray<LocationSearchResult> results = new CircularArray<>();

    HttpURLConnection connection = null;
    try {//from  ww w .ja  v  a2  s.  c om
        connection = Utils.openUrlConnection(buildPlaceSearchStartsWithUrl(startsWith));
        InputStream inputStream = connection.getInputStream();

        parseLocationSearchResults(results, inputStream);

    } catch (IOException | XmlPullParserException e) {
        Log.w(TAG, "Error parsing place search XML");
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return results;
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream getUrl(String urlString, String username, String password) {
    URL url = null;/*from  w  ww.  ja v  a  2  s. c  o  m*/
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
    InputStream is = null;
    HttpURLConnection httpConnection;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return is;
}

From source file:org.apache.mycat.advisor.common.net.http.HttpService.java

/**
 * ?URL??InputStream/* w  w w.j a  va 2  s .  c o  m*/
 *
 * @param url
 * @return
 */
public static InputStream getImageStreamByURL(String url) {
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        return conn.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.gson.util.HttpKit.java

/**
 * /*from   ww w  . j a  va  2  s  .  c om*/
 * @description 
 * ??: get 
 * @return       : 
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String get(String url, Map<String, String> params, Map<String, String> headers)
        throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException,
        UnsupportedEncodingException, IOException {
    HttpURLConnection http = null;
    if (isHttps(url)) {
        http = initHttps(initParams(url, params), _GET, headers);
    } else {
        http = initHttp(initParams(url, params), _GET, headers);
    }
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    StringBuffer bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        http.disconnect();// 
    }
    return bufferRes.toString();
}

From source file:io.cloudex.cloud.impl.google.compute.GoogleMetaData.java

/**
 * Call the metadata server, this returns details for the current instance not for
 * different instances. In order to retrieve the meta data of different instances
 * we just use the compute api, see getInstance
 * @param path//  w  w  w .  j  a  v a 2s  .c  o m
 * @return
 * @throws IOException
 */
public static String getMetaData(String path) throws IOException {
    log.debug("Retrieving metadata from server, path: " + path);
    URL metadata = new URL(METADATA_SERVER_URL + path);
    HttpURLConnection con = (HttpURLConnection) metadata.openConnection();

    // optional default is GET
    //con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("Metadata-Flavor", "Google");

    int responseCode = con.getResponseCode();

    StringBuilder response = new StringBuilder();

    if (responseCode == 200) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
    } else {
        String msg = "Metadata server responded with status code: " + responseCode;
        log.error(msg);
        throw new IOException(msg);
    }
    log.debug("Successfully retrieved metadata from server");

    return response.toString();
}

From source file:flow.visibility.tapping.OpenDayLightUtils.java

/** The function for inserting the flow */

public static void FlowEntry(String ODPURL, String ODPAccount, String ODPPassword) throws Exception {

    //String user = "admin";
    //String password = "admin";
    String baseURL = "http://" + ODPURL + "/controller/nb/v2/flowprogrammer";
    String containerName = "default";

    /** Check the connection for ODP REST API */

    try {/*  www . jav  a  2s  .  c  o m*/

        // Create URL = base URL + container
        URL url = new URL(baseURL + "/" + containerName);

        // Create authentication string and encode it to Base64
        String authStr = ODPAccount + ":" + ODPPassword;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        // Create Http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Set connection properties
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Accept", "application/json");

        // Get the response from connection's inputStream
        InputStream content = (InputStream) connection.getInputStream();

        /** The create the frame and blank pane */
        OpenDayLightUtils object = new OpenDayLightUtils();
        object.setVisible(true);

        /** Read the Flow entry in JSON Format */
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";

        /** Print line by line in Pane with Pretty JSON */
        while ((line = in.readLine()) != null) {

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);

            Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
            String json = gson.toJson(jsonObject);
            System.out.println(json);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:dictinsight.utils.io.HttpUtils.java

public static List<String> getSvnConfServer(String url) {
    BufferedReader reader = null;
    HttpURLConnection connection = null;
    List<String> seedList = new ArrayList<String>();
    try {// w  w w  .  ja  va2s .c o  m
        URL srcUrl = new URL(url);
        connection = (HttpURLConnection) srcUrl.openConnection();
        connection.setConnectTimeout(1000 * 10);
        connection.connect();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rec;
        while ((rec = reader.readLine()) != null) {
            seedList.add(rec);
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + " error!");
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null)
            connection.disconnect();
    }
    return seedList;
}

From source file:cc.vileda.sipgatesync.api.SipgateApi.java

@NonNull
private static String getUrl(final String apiUrl, final String token) throws IOException {
    final HttpURLConnection urlConnection = getConnection(apiUrl);
    urlConnection.setDoInput(true);//from w w w.  j  a v  a  2s . c  o  m
    urlConnection.setRequestMethod("GET");
    if (token != null) {
        urlConnection.setRequestProperty("Authorization", "Bearer " + token);
    }
    StringBuilder sb = new StringBuilder();
    int HttpResult = urlConnection.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();

        return sb.toString();
    } else {
        System.out.println(urlConnection.getResponseMessage());
    }

    return "";
}