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:com.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java

private HttpURLConnection getOpenedConnection(List<NameValuePair> params, String responseMethod)
        throws ConnectionException {
    HttpURLConnection urlConnection;
    try {//from   w w w. j  a v  a 2 s.c o m
        URIBuilder b = new URIBuilder(BASE_URL);
        b.addParameters(params);
        URL url = b.build().toURL();
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod(responseMethod);
        urlConnection.setReadTimeout(TIME_OUT_LENGTH);
        urlConnection.setConnectTimeout(TIME_OUT_LENGTH);
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(urlConnection.getResponseMessage());
        return urlConnection;
    } catch (URISyntaxException | IOException ex) {
        throw new ConnectionException(ex);
    }
}

From source file:com.eyekabob.util.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/* ww  w  .jav  a  2  s . c o m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
// COFFBR01 MODIFIED
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);
    }
    Util.logd("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()) {
            Object value = params.get(key);
            if (value instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) value);
            }
        }

        // 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:github.srlee309.lessWrongBookCreator.scraper.PostSectionExtractor.java

public boolean downloadFileFromURL(String fetchUrl, File outputFile)
        throws IOException, FileNotFoundException, IOException {

    HttpURLConnection c;

    //save file       
    URL url = new URL(fetchUrl);
    c = (HttpURLConnection) url.openConnection();

    //set cache and request method settings  
    c.setUseCaches(false);//from w w w  . j  av a2 s .  c  om
    c.setDoOutput(false);

    //set other headers  
    c.setRequestProperty("Content-Type", "image/jpeg");
    System.out.println(c.getContentType());
    //connect  
    c.connect();

    BufferedInputStream in = new BufferedInputStream(c.getInputStream());

    OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
    byte[] buf = new byte[256];
    int n = 0;
    while ((n = in.read(buf)) >= 0) {
        out.write(buf, 0, n);
    }
    out.flush();
    out.close();

    return true;
}

From source file:com.liveneo.plat.web.action.DownloadAction.java

public InputStream getInputStream() throws UnsupportedEncodingException, FileNotFoundException {
    // attachment,?,??;inline,??,?
    String file = "";
    if (StringUtils.equalsIgnoreCase(loadflag, "restore")) {
        file = CreateXml.backuptarget + fileName + ".zip";
    }//from  w  w  w.  j ava2 s.co m
    if (StringUtils.equalsIgnoreCase(loadflag, "excel")) {
        file = getServletContext().getRealPath("/WEB-INF/pages/template/" + fileName);
    }
    if (StringUtils.equalsIgnoreCase(loadflag, "recording")) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(fileName);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            //             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            this.getResponse().setHeader("application/x-msdownload",
                    "attachment;file=" + java.net.URLEncoder.encode(file, "UTF-8"));
            return new BufferedInputStream(connection.getInputStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //         System.out.println(getServletContext().getRealPath("/noneccrecord/ivrvoice/")+"/"+StringUtils.substringAfter(fileName, "/opt/AppServer/tomcat/webapps/noneccrecord/ivrvoice/"));

        //      file="D:/apache-tomcat-6.0.35/webapps/npworkplat/noneccrecord/ivrvoice/file1680475804236541293_ivrvoice.wav";

    }
    if (StringUtils.equalsIgnoreCase(loadflag, "license")) {
        file = fileName;
    }
    if (StringUtils.equalsIgnoreCase(loadflag, "wo")) {
        WorkOrderAction w = new WorkOrderAction();
        List<Workorder> ws = new ArrayList<Workorder>();
        ws = (List<Workorder>) this.getSession().getAttribute(sessionname);
        if (ws.size() > 0) {
            this.createWorkorderExcel(getServletContext().getRealPath("/excel/wo_info.xls"), ws,
                    "??");
        }
        file = getServletContext().getRealPath("/excel/") + "/" + fileName;
        System.out.println("file:" + file);
    }
    //
    if (StringUtils.equalsIgnoreCase(loadflag, "report")) {
        String title = this.getRequest().getParameter("title");
        title = java.net.URLDecoder.decode(title, "UTF-8");
        title = java.net.URLDecoder.decode(title, "UTF-8");
        String tvalue = this.getRequest().getParameter("tvalue");
        //
        String[] titles = title.split(",");
        //?trtd
        List<List<String>> tds = new ArrayList<List<String>>();
        String[] tr = tvalue.split(";");
        for (int j = 0; j < tr.length; j++) {
            List<String> td = new ArrayList<String>();
            String[] fields = tr[j].split(",");
            for (String v : fields) {
                if (v == null) {
                    v = "";
                }
                td.add(v);
            }
            tds.add(td);
        }
        //?excel
        ExcelUtils.exportExcel(getServletContext().getRealPath("/excel/") + "/" + fileName, titles, tds);
        file = getServletContext().getRealPath("/excel/") + "/" + fileName;
    }
    //?
    if (StringUtils.equalsIgnoreCase(loadflag, "commonexcel")) {
        String title = this.getRequest().getParameter("title");
        title = java.net.URLDecoder.decode(title, "UTF-8");
        title = java.net.URLDecoder.decode(title, "UTF-8");
        //
        String[] titles = title.split(",");
        //?trtd
        List<List<String>> tds = new ArrayList<List<String>>();
        tds = (List<List<String>>) this.getSession().getAttribute(sessionname);
        //?excel
        ExcelUtils.exportExcel(getServletContext().getRealPath("/excel/") + "/" + fileName, titles, tds);
        file = getServletContext().getRealPath("/excel/") + "/" + fileName;
    }
    this.getResponse().setHeader("application/x-msdownload",
            "attachment;file=" + java.net.URLEncoder.encode(file, "UTF-8"));
    // fileName?
    return new BufferedInputStream(new FileInputStream(file));
}

From source file:io.apiman.manager.ui.server.servlets.ApiManagerProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from   w w  w  .j av a2 s. com*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    StringBuilder url = new StringBuilder();

    String endpoint = getConfig().getManagementApiEndpoint();
    if (endpoint == null) {
        endpoint = getDefaultEndpoint(req);
    }

    url.append(endpoint);
    if (!url.toString().endsWith("/")) { //$NON-NLS-1$
        url.append('/');
    }
    String pathInfo = req.getPathInfo();
    if (pathInfo != null && pathInfo.startsWith("/")) { //$NON-NLS-1$
        url.append(pathInfo.substring(1));
    } else {
        url.append(pathInfo);
    }

    String authHeaderValue = null;
    ApiAuthType authType = getConfig().getManagementApiAuthType();
    switch (authType) {
    case basic: {
        String username = getConfig().getManagementApiAuthUsername();
        String password = getConfig().getManagementApiAuthPassword();
        String encoded = base64Encode(username + ":" + password); //$NON-NLS-1$
        authHeaderValue = "Basic " + encoded; //$NON-NLS-1$
        break;
    }
    case authToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        authHeaderValue = "AUTH-TOKEN " + token; //$NON-NLS-1$
        break;
    }
    case bearerToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        authHeaderValue = "Bearer " + token; //$NON-NLS-1$
        break;
    }
    case samlBearerToken: {
        ITokenGenerator tokenGenerator = getTokenGenerator();
        BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req);
        String token = creds.getToken();
        // TODO base64 decode the token, then re-encode it with "SAML-BEARER-TOKEN:"
        authHeaderValue = "Basic SAML-BEARER-TOKEN:" + token; //$NON-NLS-1$
        break;
    }
    }

    URL remoteUrl = new URL(url.toString());
    HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection();
    InputStream remoteIS = null;
    OutputStream responseOS = null;
    try {
        if (authHeaderValue != null) {
            remoteConn.setRequestProperty("Authorization", authHeaderValue); //$NON-NLS-1$
        }
        remoteConn.connect();
        Map<String, List<String>> headerFields = remoteConn.getHeaderFields();
        for (String headerName : headerFields.keySet()) {
            if (headerName == null) {
                continue;
            }
            if (EXCLUDE_HEADERS.contains(headerName)) {
                continue;
            }
            String headerValue = remoteConn.getHeaderField(headerName);
            resp.setHeader(headerName, headerValue);
            if (url.toString().contains("apiregistry")) { //$NON-NLS-1$
                String type = "json"; //$NON-NLS-1$
                if (url.toString().endsWith("xml")) { //$NON-NLS-1$
                    type = "xml"; //$NON-NLS-1$
                }
                resp.setHeader("Content-Disposition", "attachment; filename=api-registry." + type); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$
        remoteIS = remoteConn.getInputStream();
        responseOS = resp.getOutputStream();
        IOUtils.copy(remoteIS, responseOS);
        resp.flushBuffer();
    } catch (Exception e) {
        resp.sendError(500, e.getMessage());
    } finally {
        IOUtils.closeQuietly(responseOS);
        IOUtils.closeQuietly(remoteIS);
    }
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 *  JDK???//from ww  w.j  a  v  a  2 s .c  o  m
 */

private void fetchContentByJDKConnection(HttpServletResponse response, String contentUrl) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(contentUrl).openConnection();
    // Socket
    connection.setReadTimeout(TIMEOUT_SECONDS * 1000);
    try {
        connection.connect();

        // ?
        InputStream input;
        try {
            input = connection.getInputStream();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, contentUrl + " is not found.");
            return;
        }

        // Header
        response.setContentType(connection.getContentType());
        if (connection.getContentLength() > 0) {
            response.setContentLength(connection.getContentLength());
        }

        // 
        OutputStream output = response.getOutputStream();
        try {
            // byte?InputStreamOutputStream, ?4k.
            IOUtils.copy(input, output);
            output.flush();
        } finally {
            // ??InputStream.
            IOUtils.closeQuietly(input);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:com.webcohesion.ofx4j.client.net.OFXV1Connection.java

/**
 * Send the specified buffer to the specified URL.
 *
 * @param url The URL.//from  w  w  w .ja  v a 2 s  . c o  m
 * @param outBuffer The buffer.
 * @return The response.
 */
protected InputStream sendBuffer(URL url, ByteArrayOutputStream outBuffer)
        throws IOException, OFXConnectionException {
    HttpURLConnection connection = openConnection(url);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-ofx");
    connection.setRequestProperty("Content-Length", String.valueOf(outBuffer.size()));
    connection.setRequestProperty("Accept", "*/*, application/x-ofx");
    connection.setDoOutput(true);
    connection.connect();

    OutputStream out = connection.getOutputStream();
    out.write(outBuffer.toByteArray());

    InputStream in;
    int responseCode = connection.getResponseCode();
    if (responseCode >= 200 && responseCode < 300) {
        in = connection.getInputStream();
    } else if (responseCode >= 400 && responseCode < 500) {
        throw new OFXServerException("Error with client request: " + connection.getResponseMessage(),
                responseCode);
    } else {
        throw new OFXServerException(
                "Invalid response code from OFX server: " + connection.getResponseMessage(), responseCode);
    }

    return in;
}

From source file: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/* w  ww  . ja va 2 s .  c o  m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
@Deprecated
public static String openUrl(String url, String method, Bundle params) throws 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);
    }
    Utility.logd("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()) {
            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());

        try {
            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();
        } finally {
            os.close();
        }
    }

    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:it.govpay.web.rs.Check.java

@GET
@Path("/pdd")
public Response verificaPDD(@QueryParam(value = "matchString") String matchString) {
    Logger log = LogManager.getLogger();
    try {//  ww  w.j  a va 2s .c om
        try {
            URL url = GovpayConfig.getInstance().getUrlPddVerifica();
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String checkResult = null;
            conn.connect();

            int responseCode = conn.getResponseCode();

            String bodyResponse = null;

            if (responseCode > 299) {
                checkResult = "Ottenuto response code [" + responseCode + "] durante la connessione a [" + url
                        + "]";
            }

            if (matchString != null) {
                checkResult = null;

                if (responseCode < 300) {
                    if (conn.getInputStream() != null) {
                        bodyResponse = new String(
                                conn.getInputStream() != null ? IOUtils.toByteArray(conn.getInputStream())
                                        : new byte[] {});
                    }
                } else {
                    if (conn.getErrorStream() != null) {
                        bodyResponse = new String(
                                conn.getErrorStream() != null ? IOUtils.toByteArray(conn.getErrorStream())
                                        : new byte[] {});
                    }
                }

                if (bodyResponse == null || !bodyResponse.contains(matchString))
                    checkResult = "Ottenuta risposta che non contiene la matchString [" + matchString
                            + "] durante la connessione a [" + url + "]";
            }

            if (checkResult != null)
                throw new Exception(checkResult);

        } catch (Exception e) {
            log.error("Errore di connessione alla PDD", e);
            throw new Exception("Errore di connessione alla PDD: " + e.getMessage());
        }

        return Response.ok().build();
    } catch (Exception e) {
        return Response.status(500).entity(e.getMessage()).build();
    }
}

From source file:com.captix.scan.social.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /* w  w  w  .j a  v  a2s  .  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);
    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")) {
            @SuppressWarnings("deprecation")
            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;
}