Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:net.sf.jabref.logic.net.URLDownload.java

private URLConnection openConnection() throws IOException {
    URLConnection connection = source.openConnection();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }//  w  w  w . ja  v  a2  s .com
    if (!postData.isEmpty()) {
        connection.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(postData);
        }

    }
    // this does network i/o: GET + read returned headers
    connection.connect();

    return connection;
}

From source file:dashboard.VersionCheck.java

public int importVersionCheckLog(int n, String apiuser, String apipass, String IPfile, String ERRfile,
        String versionCheckURL, String versionCheckPass, String API_KEY, String TOKEN, String startTime)
        throws Exception {
    int lines = 0;
    String ip = "";
    String registrant = "";
    Mixpanel mix = new Mixpanel();
    String build = "";
    String eventTime = "5/22/13 0:01 AM";
    int x = 0;/*from  w  w  w. j a  v a 2s. c o  m*/
    int mixpanelStatus = 0;
    int errors = 0;
    String prevIP = "";
    int index = 0;
    Registrant r;
    ArrayList<Registrant> rList = new ArrayList<Registrant>();
    ArrayList<Registrant> eList = new ArrayList<Registrant>();
    IPList ipl = new IPList();
    IPList errl = new IPList();
    Whois w = new Whois(apiuser, apipass);
    SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yy h:mm a");

    long event = 0;
    long from = sdf.parse(startTime).getTime();
    int nn = 1;

    System.out.println(">>>  Version Check log - " + versionCheckURL);
    URL logURL = new URL(versionCheckURL);
    String base64EncodedString = Base64.encodeBase64String(StringUtils.getBytesUtf8(versionCheckPass));

    URLConnection conn = logURL.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + base64EncodedString);

    InputStream in = conn.getInputStream();
    BufferedReader br = null;

    try {
        br = new BufferedReader(new InputStreamReader(in));
        String inputLine = br.readLine();

        // Skip first line (headers)
        if (inputLine != null)
            inputLine = br.readLine();

        // Load list of IP - REGISTRANT               
        ipl.loadList(rList, IPfile);
        ipl.printList(rList, 5);

        // Loop - limited to n cycles (parameter defined by user)
        while (inputLine != null & lines < n) {
            String[] dataArray = inputLine.split(",");
            x = 0;
            for (String ttt : dataArray)
                x++;
            if (x == 3) {
                ip = dataArray[0];
                build = dataArray[1];
                eventTime = dataArray[2];
            } else if (x == 4) {
                // Line format is corrupted (2 ip's)
                errors++;
                ip = dataArray[1];
                build = dataArray[2];
                eventTime = dataArray[3];
            }

            event = sdf.parse(eventTime).getTime();
            if (event < from) {
                nn++;
                //System.out.print(nn + ", ");   
                inputLine = br.readLine(); // Read next line of data.
                continue;
            }

            if (lines == 0) {
                System.out.println("------  Skipped " + nn + " events --------");
                System.out.println();
            }

            if (ip != prevIP) {
                prevIP = ip;

                index = ipl.ipInList(ip, rList);
                if (index >= 0) {
                    r = rList.get(index);
                    registrant = r.name;
                    // Update counter for this IP
                    r.counter = r.counter + 1;
                    rList.set(index, r);
                } else {
                    // WHOIS - Check registrant of this IP address
                    registrant = w.whoisIP(ip);

                    // if there was an error, try again
                    if (registrant.equals("ERROR"))
                        registrant = w.whoisIP(ip);

                    // if there was a second error, add it to errors list
                    if (registrant.equals("ERROR")) {
                        eList.add(new Registrant(ip, registrant, 1));
                    } else {
                        // If name includes a comma, exclude the comma
                        registrant = registrant.replace(",", "");
                        rList.add(new Registrant(ip, registrant, 1));
                    }
                }
            }

            inputLine = br.readLine(); // Read next line of data.
            lines++;

            System.out.println(">> " + lines + " - " + eventTime + "  " + ip + " - " + registrant);

            // Track the event in Mixpanel (using the POST import) - event time is in the PAST
            mix.postVersionCheckToMixpanel(API_KEY, TOKEN, ip, registrant, "Version Check", eventTime, build);

        } // while
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Close the file once all data has been read.
        if (br != null)
            br.close();

        ipl.printList(rList, 5);
        ipl.saveList(rList, IPfile);

        if (!eList.isEmpty()) {
            sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
            String fName = ERRfile + sdf.format(new Date()) + ".txt";

            System.out.println("\n>>> " + eList.size() + " DomainTools errors:");
            errl.saveList(eList, fName);
        } else
            System.out.println("\n>>> No DomainTools errors");

        return lines;
    }
}

From source file:org.jgrades.monitor.restart.SystemStateServiceImpl.java

private void setAuthProperty(URLConnection connection) {
    if (masterScriptUser != null && masterScriptPwd != null) {
        String userPass = masterScriptUser + ":" + masterScriptPwd;
        String encoded = Base64.getEncoder().encodeToString(userPass.getBytes(Charset.defaultCharset()));
        connection.setRequestProperty("Authorization", "Basic " + encoded);
    }/*from ww w  . j  a  v  a2  s . c  o m*/
}

From source file:com.enonic.cms.core.http.HTTPService.java

private URLConnection setUpConnection(String address, int timeoutMs, int readTimeoutMs) throws IOException {
    URL url = new URL(address);
    URLConnection urlConn = url.openConnection();
    urlConn.setConnectTimeout(timeoutMs > 0 ? timeoutMs : DEFAULT_CONNECTION_TIMEOUT);
    urlConn.setReadTimeout(readTimeoutMs > 0 ? readTimeoutMs : DEFAULT_READ_TIMEOUT);
    urlConn.setRequestProperty("User-Agent", userAgent);
    String userInfo = url.getUserInfo();
    if (StringUtils.isNotBlank(userInfo)) {
        String userInfoBase64Encoded = new String(Base64.encodeBase64(userInfo.getBytes()));
        urlConn.setRequestProperty("Authorization", "Basic " + userInfoBase64Encoded);
    }//from  w  w w  . ja  v a2  s  . c om
    return urlConn;

}

From source file:org.messic.server.api.musicinfo.duckduckgoimages.MusicInfoDuckDuckGoImages.java

private String search(String baseUrl) throws IOException {
    URL url = new URL(baseUrl);
    Proxy proxy = getProxy();/*from   www .  ja  v a2 s.  c  om*/
    URLConnection connection = (proxy != null ? url.openConnection(proxy) : url.openConnection());
    connection.setRequestProperty("User-Agent", "Messic/1.0 +http://spheras.github.io/messic/");

    InputStream is = connection.getInputStream();
    List<String> urlImages = getUrlImages(is);

    String htmlCode = "<script type='text/javascript'>";
    htmlCode = htmlCode + "  function musicInfoDuckDuckGoImagesDestroy(){";
    htmlCode = htmlCode + "       $('.messic-musicinfo-duckduckgoimages-overlay').remove();";
    htmlCode = htmlCode + "  }";
    htmlCode = htmlCode + "  function musicInfoDuckDuckGoImagesShow(url){";
    htmlCode = htmlCode
            + "      var code= '<div class=\"messic-musicinfo-duckduckgoimages-overlay\" onclick=\"musicInfoDuckDuckGoImagesDestroy()\">';";
    htmlCode = htmlCode + "      code=code+'  <image src=\"'+url+'\" />';";
    htmlCode = htmlCode
            + "      code=code+'  <a class=\"messic-musicinfo-duckduckgoimages-zoom\" href=\"'+url+'\" target=\"_blank\"></a>';";
    htmlCode = htmlCode + "      code=code+'</div>';";
    htmlCode = htmlCode + "      $(code).hide().appendTo('body').fadeIn();";
    htmlCode = htmlCode + "  }";
    htmlCode = htmlCode + "</script>";

    htmlCode = htmlCode + "<div class=\"messic-musicinfo-duckduckgoimages-imagecontainer\">";
    htmlCode = htmlCode
            + "  <div>we &lt;3 <a href=\"http://www.duckduckgo.com\" target=\"_blank\">DuckDuckGo</a></div>";
    for (String urlimage : urlImages) {
        htmlCode = htmlCode + " <img src=\"" + urlimage + "\" onclick=\"musicInfoDuckDuckGoImagesShow('"
                + urlimage + "')\"/>";
    }
    htmlCode = htmlCode + "</div>";

    return htmlCode;
}

From source file:dashboard.ImportCSV.java

public Integer importCSVlog(String u, int n) throws Exception {
    String s = "";
    Integer lines = 0;//from   w w  w . jav  a2s . c o m
    URL gigaURL = new URL(u);

    String loginPassword = "marketing:gigaspac3s";
    String base64EncodedString = Base64.encodeBase64String(StringUtils.getBytesUtf8(loginPassword));
    URLConnection conn = gigaURL.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + base64EncodedString);
    InputStream in = conn.getInputStream();

    BufferedReader br = null;

    try {
        br = new BufferedReader(new InputStreamReader(in));

        String inputLine = br.readLine();
        // Skip first line (headers)
        if (inputLine != null)
            inputLine = br.readLine();

        String ip = "";
        String build = "";
        String eventTime = "3/14/13 10:10 AM";
        int x = 0;
        // Loop - limited to n cycles (parameter defined by user)
        while (inputLine != null & lines < n) {
            String[] dataArray = inputLine.split(",");
            //for (String item : dataArray) s = item + "\t";
            x = 0;
            for (String ttt : dataArray)
                x++;
            if (x == 3) {

                ip = dataArray[0];
                build = dataArray[1];
                eventTime = dataArray[2];
            } else if (x == 4) {
                // Line format is corrupted (2 ip's)
                errors++;
                ip = dataArray[1];
                build = dataArray[2];
                eventTime = dataArray[3];
            }

            //s = s + "\n"; 
            inputLine = br.readLine(); // Read next line of data.
            lines++;

            // Track the event in Mixpanel (using the Java API)  - event time is TODAY
            //sendEventToMixpanel(ip, "Product Activation", eventTime, build);

            // Track the event in Mixpanel (using the POST import) - event time is as indicated - in the PAST
            postCSVEventToMixpanel(ip, "Version Check", eventTime, build);

        } // while
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Close the file once all data has been read.
        if (br != null)
            br.close();
        return lines;
    }
}

From source file:com.nextgis.mobile.util.ApkDownloader.java

@Override
protected String doInBackground(String... params) {
    try {/*  www . j a  va  2s  . co  m*/
        URL url = new URL(params[0]);
        mApkPath = Environment.getExternalStorageDirectory() + "/download/"
                + Uri.parse(params[0]).getLastPathSegment();
        URLConnection connection = url.openConnection();
        if (url.getProtocol().equalsIgnoreCase("https"))
            connection.setRequestProperty("Authorization", params[1]);

        connection.connect();
        int fileLength = connection.getContentLength() / 1024;
        InputStream input = new BufferedInputStream(connection.getInputStream());
        OutputStream output = new FileOutputStream(mApkPath);

        byte data[] = new byte[1024];
        long total = 0;
        int count;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress((int) total / 1024, fileLength);
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();

        return null;
    } catch (MalformedURLException e) {
        return mActivity.getString(R.string.error_invalid_url);
    } catch (IOException e) {
        return mActivity.getString(R.string.error_network_unavailable);
    }
}

From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java

/**
 * This method is used to retrieve assets via publisher assets list endpoint
 *
 * @param sessionId String of valid session ID
 * @return JSON ARRAY of gadgets//from  ww w.  ja v a 2  s.  c om
 */
private JsonArray getAssets(String sessionId) throws IOException {
    BufferedReader input = null;
    String listAssetsEndpoint = getBaseUrl() + PUBLISHER_APIS_LIST_GADGETS_ENDPOINT;
    //construct endpoint which retrieves list of gadgets
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Get Assets via REST endpoint using sessionID: " + sessionId);
        }
        URL endpointUrl = new URL(listAssetsEndpoint);
        URLConnection urlConn = endpointUrl.openConnection();
        urlConn.setRequestProperty("Accept", "application/json");
        urlConn.setRequestProperty(COOKIE, JSESSIONID + "=" + sessionId + ";");
        // SessionId Cookie
        urlConn.connect();
        //GET response data
        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        JsonElement elem = parser.parse(input);

        // parse response to a JasonArray
        return elem.getAsJsonObject().getAsJsonArray(ASSET_LIST_KEY);
    } catch (MalformedURLException e) {
        LOG.error(getAssetRetrievingErrorMassage(listAssetsEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getAssetRetrievingErrorMassage(listAssetsEndpoint), e);
        throw e;
    } finally {
        if (input != null) {
            try {
                input.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close the connection", e);
            }
        }
    }
}

From source file:org.t3.metamediamanager.OmdbProvider.java

/**
 * Connects to the omdb API and return the JSONObject associates with the query.
 * @param s/*w w  w.  j a va 2 s .c o  m*/
 *       The query.
 * @param mode
 *       The way of your query :
 *          -s = general query (with the MovieTitle)
 *          -i = precise query (with the MovieId)
 * @return A JSONObject which contains the data.
 * @throws ProviderException
 */
private JSONObject getJSON(String s, char mode) throws ProviderException {
    try {
        if (mode == 'i') {
            query = String.format("i=%s", URLEncoder.encode(s, charset));
        } else if (mode == 's') {
            query = String.format("s=%s", URLEncoder.encode(s, charset));
        }
        URLConnection connection = new URL(url + "?" + query).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        InputStream response = connection.getInputStream();
        String rep = convertStreamToString(response);
        return convertStringToJSON(rep);
    } catch (IOException e) {
        throw new ProviderException("Erreur d'accs  l'API !");
    }
}

From source file:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

/**
 * Get timestamp token - communications layer
 * /* www  .j  a v a  2s .com*/
 * @return - byte[] - TSA response, raw bytes (RFC 3161 encoded)
 */
protected byte[] getTSAResponse(byte[] requestBytes) throws IOException {
    // Setup the TSA connection

    URL tspUrl = new URL(tspServer);
    URLConnection tsaConnection = tspUrl.openConnection();

    tsaConnection.setDoInput(true);
    tsaConnection.setDoOutput(true);
    tsaConnection.setUseCaches(false);
    tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
    // tsaConnection.setRequestProperty("Content-Transfer-Encoding",
    // "base64");
    tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");

    OutputStream out = tsaConnection.getOutputStream();
    out.write(requestBytes);
    out.close();

    // Get TSA response as a byte array
    InputStream inp = tsaConnection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
        baos.write(buffer, 0, bytesRead);
    }
    byte[] respBytes = baos.toByteArray();

    String encoding = tsaConnection.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("base64")) {
        respBytes = new Base64().decode(respBytes);
    }
    return respBytes;
}