Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private Bitmap getIconBitmap(Context context, String iconUrl) {
    try {// w  w  w  . j a  v a 2  s .c  om
        URL uRL = new URL(iconUrl);
        HttpURLConnection connection = (HttpURLConnection) uRL.openConnection();
        String cookie = CookieManager.getInstance().getCookie(iconUrl);
        if (null != cookie) {
            connection.setRequestProperty(SM.COOKIE, cookie);
        }
        connection.connect();
        if (200 == connection.getResponseCode()) {
            InputStream input = connection.getInputStream();
            if (input != null) {
                Environment.getDownloadCacheDirectory();
                File ecd = context.getExternalCacheDir();
                File file = new File(ecd, "pushIcon.png");
                OutputStream outStream = new FileOutputStream(file);
                byte buf[] = new byte[8 * 1024];
                while (true) {
                    int numread = input.read(buf);
                    if (numread == -1) {
                        break;
                    }
                    outStream.write(buf, 0, numread);
                }
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                return bitmap;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.ffremont.microservices.springboot.node.services.MsService.java

/**
 * Retourne le flux  lire/*  w  w w .  j a  va 2s. c  o m*/
 *
 * @param msName
 * @return
 */
public Path getBinary(String msName) {
    MicroServiceRest ms = this.getMs(msName);

    if (ms == null) {
        return null;
    }

    MasterUrlBuilder builder = new MasterUrlBuilder(cluster, node, masterhost, masterPort, masterCR);
    builder.setUri(msName + "/binary");

    Path tempFileBinary = null;
    try {
        tempFileBinary = Files.createTempFile("node", "jarBinary");
        HttpURLConnection managerConnection = (HttpURLConnection) (new URL(builder.build())).openConnection();
        managerConnection.setRequestProperty("Authorization", "Basic "
                .concat(new String(Base64.getEncoder().encode((username + ":" + password).getBytes()))));
        managerConnection.setRequestProperty("Accept", "application/java-archive");
        managerConnection.connect();

        if (managerConnection.getResponseCode() != 200) {
            LOG.warn("Manager : rcupration impossible, statut {}", managerConnection.getResponseCode());
            return tempFileBinary;
        }

        FileOutputStream fos = new FileOutputStream(tempFileBinary.toFile());
        try (InputStream is = managerConnection.getInputStream()) {
            byte[] buffer = new byte[10240]; // 10ko
            int read;
            while (-1 != (read = is.read(buffer))) {
                fos.write(buffer, 0, read);
            }
            fos.flush();
            is.close();
        }
    } catch (IOException ex) {
        LOG.error("Impossible de rcuprer le binaire", ex);
        if (tempFileBinary != null) {
            try {
                Files.delete(tempFileBinary);
            } catch (IOException e) {
            }
        }
    }

    return tempFileBinary;
}

From source file:nl.b3p.viewer.stripes.ProxyActionBean.java

private Resolution proxyArcIMS() throws Exception {

    HttpServletRequest request = getContext().getRequest();

    if (!"POST".equals(request.getMethod())) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }/*from  w w  w  . jav a 2s  .  c  o m*/

    Map params = new HashMap(getContext().getRequest().getParameterMap());
    // Only allow these parameters in proxy request
    params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName"));
    URL theUrl = new URL(url);
    // Must not allow file / jar etc protocols, only HTTP:
    String path = theUrl.getPath();
    for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) {
        if (path.length() == theUrl.getPath().length()) {
            path += "?";
        } else {
            path += "&";
        }
        path += URLEncoder.encode(param.getKey(), "UTF-8") + "="
                + URLEncoder.encode(param.getValue()[0], "UTF-8");
    }
    theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);

    // TODO logging for inspecting malicious proxy use

    ByteArrayOutputStream post = new ByteArrayOutputStream();
    IOUtils.copy(request.getInputStream(), post);

    // This check makes some assumptions on how browsers serialize XML
    // created by OpenLayers' ArcXML.js write() function (whitespace etc.),
    // but all major browsers pass this check
    if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }

    final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    connection.connect();
    try {
        IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
    } finally {
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
    }

    return new StreamingResolution(connection.getContentType()) {
        @Override
        protected void stream(HttpServletResponse response) throws IOException {
            try {
                IOUtils.copy(connection.getInputStream(), response.getOutputStream());
            } finally {
                connection.disconnect();
            }

        }
    };
}

From source file:barcamp.com.facebook.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String/*from w  w w.j  a  v  a  2 s.  co m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.get(key) instanceof byte[]) {
                //if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Sends a POST request/*from   www  .java 2s  .com*/
 *
 * @param url           URL
 * @param postData      Post request body
 * @param encoding      Post request body encoding
 * @param contentType   Body content type
 * @param compress      If true - compress bod
 * @param readTimeout   Read timeout
 * @param socketTimeout Socket timeout
 * @return Response
 */
public static String postRequest(URL url, String postData, String encoding, String contentType,
        boolean compress, int readTimeout, int socketTimeout) {
    HttpURLConnection connection = null;
    OutputStream outputStream = null;

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }
        if (compress) {
            connection.setRequestProperty("Content-Encoding", "gzip");
        }
        connection.setConnectTimeout(socketTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setDoOutput(true);
        connection.connect();
        if (postData != null) {
            outputStream = connection.getOutputStream();

            if (compress) {
                outputStream = new GZIPOutputStream(outputStream);
            }

            if (encoding != null) {
                IOUtils.write(postData, outputStream, encoding);
            } else {
                IOUtils.write(postData, outputStream);
            }

            if (compress) {
                ((GZIPOutputStream) outputStream).finish();
            } else {
                outputStream.flush();
            }
        }

        return IOUtils.toString(connection.getInputStream(), encoding);
    } catch (Exception ex) {
        LOG.error("Error posting request to {}, post data length={}\r\n", url, StringUtils.length(postData),
                ex);
        // Ignoring exception
        return null;
    } finally {
        IOUtils.closeQuietly(outputStream);

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

From source file:com.enefsy.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String//from   w ww . j a  v a  2s.c om
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.aegiswallet.tasks.GetCurrencyInfoTask.java

@Override
protected Void doInBackground(String... strings) {

    Log.d(TAG, "inside currency info task...");

    if (fileExistance(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME)
            && !shouldRefreshFile(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME)) {
        return null;
    }//from ww  w .j  a  va 2s.c o m

    HttpURLConnection urlConnection = null;
    URL url = null;
    jsonObject = null;
    InputStream inStream = null;
    try {
        url = new URL(urlString.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        inStream = urlConnection.getInputStream();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
        String temp, response = "";
        while ((temp = bReader.readLine()) != null) {
            response += temp;
        }
        jsonObject = (JSONObject) new JSONTokener(response).nextValue();
    } catch (Exception e) {
    } finally {
        if (inStream != null) {
            try {
                // this will close the bReader as well
                inStream.close();
            } catch (IOException ignored) {
                Log.e("Currency Task", "File Close IO Exception: " + ignored.getMessage());
            }
        }
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (jsonObject != null) {

        try {
            FileOutputStream fos = context.getApplicationContext()
                    .openFileOutput(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME, Context.MODE_PRIVATE);
            fos.write(jsonObject.toString().getBytes());
            fos.close();
        } catch (IOException e) {
            Log.e("Currency Task", "Cannot save or create file " + e.getMessage());
        }
    }
    return null;
}

From source file:com.ble.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from w  ww  . ja va  2  s.  co  m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    //url+="&fields=email";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public byte[] post(String url, byte[] data) throws IOException {

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.setDoOutput(true);/*from   www .  j  a va 2 s  . co  m*/
    connection.setDoInput(true);
    connection.connect();

    // Send the request
    connection.getOutputStream().write(data);
    connection.getOutputStream().flush();
    connection.getOutputStream().close();

    // Check for errors
    checkForErrors(connection);

    // Get the result
    return disconnectAndReturn(connection, IOUtils.toByteArray(connection.getInputStream()));
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public String postString(String url, String data) throws IOException {

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.setDoOutput(true);/*from  w  w  w  .jav  a 2s  . c  om*/
    connection.setDoInput(true);
    connection.connect();

    // Send the request
    connection.getOutputStream().write(data.getBytes("ISO-8859-1"));
    connection.getOutputStream().flush();
    connection.getOutputStream().close();

    // Check for errors
    checkForErrors(connection);

    // Get the result
    return disconnectAndReturn(connection, IOUtils.toString(connection.getInputStream(), "ISO-8859-1"));
}