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.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer16(String hash) throws IOException {
    URL url;/*from   w  w  w. j  a  va2s .  co  m*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer16 + "user=" + username + "&sessionId=" + accessToken + "&serverId=" + hash;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.connect();

    if (con.getResponseCode() != 200) {
        throw new IOException("Auth server rejected username and password");
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (!"OK".equals(reply)) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:FainClasses.HttpBasicAuth.java

public static void auth() {

    String sHTML = "Can not load page";
    URL url;/*ww w  . j  a  v  a2 s  . c  o  m*/
    InputStream is;
    BufferedReader buff = null;

    try {
        url = new URL("http://vrgaz.ru/lk/index.php?page=ls&lss=1600013620");
        url.getAuthority();

        String encoding = Base64.encodeBase64String("md_dimka@mail.ru:ufpyflt;ls".getBytes());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Cookie", "PHPSESSID=343266771f5de3a489ba82fe79809854");
        // connection.
        //connection.setRequestProperty("Authorization", "Basic " + encoding);

        /*connection.setRequestProperty("avl","md_dimka@mail.ru");
        connection.setRequestProperty("avp","ufpyflt;ls");
         */
        //connection.setRequestProperty("page", "ls");
        //connection.setRequestProperty("lss", "1600013620");

        //URL url = new URL("http://vrgaz.ru/lk/");  
        // url = new URL(sUrl);
        //is = url.openStream();
        is = connection.getInputStream();
        buff = new BufferedReader(new InputStreamReader(is, "windows-1251"));
        StringBuilder page = new StringBuilder();
        String tmp;
        while ((tmp = buff.readLine()) != null) {
            page.append(tmp).append("\n");
        }

        sHTML = page.toString();
        System.out.println(sHTML);
        //            InputStream content = (InputStream) connection.getInputStream();
        //            BufferedReader in
        //                    = new BufferedReader(new InputStreamReader(content));
        //            String line;
        //            while ((line = in.readLine()) != null) {
        //                System.out.println(line);
        //            }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.lurencun.cfuture09.androidkit.http.Http.java

/**
 * //from   ww w.  j  a  v  a  2s. co  m
 *
 * @param url
 *            ?
 * @param savePath
 *            ??
 * @param overwrite
 *            ?
 * @throws IOException
 *             ??io
 */
public static void download(String url, File savePath, boolean overwrite) throws IOException {
    if (savePath == null) {
        throw new IOException("the second parameter couldn't be null");
    }
    if (savePath.exists() && (!overwrite || savePath.isDirectory())) {
        throw new IOException("the file specified is exist or cannot be overwrite");
    }
    savePath.getParentFile().mkdirs();

    HttpURLConnection connection = null;
    InputStream input = null;
    FileOutputStream output = null;
    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        input = connection.getInputStream();
        output = new FileOutputStream(savePath);
        byte[] buffer = new byte[BUFFER_SIZE];
        int readSize = 0;
        while ((readSize = input.read(buffer)) != -1) {
            output.write(buffer, 0, readSize);
        }
        output.flush();
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPut(String url, String param, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(PUT :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    param = param.replace("\"", "%22").replace("{", "%7B").replace("}", "%7D").replace(",", "%2C")
            .replace("[", "%5B").replace("]", "%5D").replace(":", "%3A").replace(" ", "+");
    String processedURL = url + "?MFAChallenge=" + param;//"%7B%22loginForm%22%3A%7B%22formType%22%3A%22token%22%2C%22mfaTimeout%22%3A%2299380%22%2C%22row%22%3A%5B%7B%22id%22%3A%22token_row%22%2C%22label%22%3A%22Security+Key%22%2C%22form%22%3A%220001%22%2C%22fieldRowChoice%22%3A%220001%22%2C%22field%22%3A%5B%7B%22id%22%3A%22token%22%2C%22name%22%3A%22tokenValue%22%2C%22type%22%3A%22text%22%2C%22value%22%3A%22123456%22%2C%22isOptional%22%3Afalse%2C%22valueEditable%22%3Atrue%2C%22maxLength%22%3A%2210%22%7D%5D%7D%5D%7D%7D";
    URL myURL = new URL(processedURL);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + processedURL.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);/* ww  w .  j a  v a2 s .c  o m*/
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP PUT' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:RemoteDeviceDiscovery.java

public static void postDevice(RemoteDevice d) throws Exception {
    String url = "http://bluetoothdatabase.com/datacollection/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "blucat");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = deviceJson(d);

    // Send post request
    con.setDoOutput(true);/*from   ww w  . j  ava 2s .c om*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
}

From source file:com.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {/*from   w  w  w  .j  a v a  2  s  . c  o  m*/
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:biz.mosil.webtools.MosilWeb.java

/**
 * ? InputStream/*from ww w .j  a  va 2s .  c o  m*/
 * */
public static final InputStream getInputStream(final String _url) {
    InputStream result = null;

    try {
        URL url = new URL(_url);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection)) {
            throw new IOException("This URL Can't Connect!");
        }

        HttpURLConnection httpConn = (HttpURLConnection) conn;
        //????
        httpConn.setAllowUserInteraction(false);
        //??
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        final int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            result = httpConn.getInputStream();
        }

    } catch (MalformedURLException _ex) {
        Log.e("getInputStream", "Malformed URL Exception: " + _ex.toString());
    } catch (IOException _ex) {
        Log.e("getInputStream", "IO Exception: " + _ex.toString());
    }
    return result;
}

From source file:chen.android.toolkit.network.HttpConnection.java

/**
 * </br><b>title : </b>      ????POST??
 * </br><b>description :</b>????POST??
 * </br><b>time :</b>      2012-7-8 ?4:34:08
 * @param method         ??//www.ja va2 s  .c  om
 * @param url            POSTURL
 * @param datas            ????
 * @return               ???
 * @throws IOException
 */
private static InputStream connect(String method, URL url, byte[]... datas) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod(method);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    conn.setConnectTimeout(6 * 1000);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");
    OutputStream outputStream = conn.getOutputStream();
    for (byte[] data : datas) {
        outputStream.write(data);
    }
    outputStream.close();
    return conn.getInputStream();
}

From source file:com.illusionaryone.FrankerZAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;//from  ww  w  . j  a  v a 2  s  . c  o  m
    HttpURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.printStackTrace(ex);
            }
    }

    return (jsonResult);
}

From source file:com.max2idea.android.fwknop.Fwknop.java

public static String getExternalIP() {
    URL Url = null;//from   w  w w .  j av a 2s  .  c  o  m
    HttpURLConnection Conn = null;
    InputStream InStream = null;
    InputStreamReader Isr = null;
    String extIP = "";

    try {
        Url = new java.net.URL("http://ifconfig.me/ip");
        Conn = (HttpURLConnection) Url.openConnection();
        InStream = Conn.getInputStream();
        Isr = new java.io.InputStreamReader(InStream);
        BufferedReader Br = new java.io.BufferedReader(Isr);
        extIP = Br.readLine();
        Log.v("External IP", "Your external IP address is " + extIP);
    } catch (Exception ex) {
        Logger.getLogger(Fwknop.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        //            Isr.close();
        //            InStream.close();
        Conn.disconnect();
    }
    return extIP;

}