Example usage for java.net URLConnection addRequestProperty

List of usage examples for java.net URLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage


From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's details.
 *
 * @return true if successful./*from  w  ww. j  a v a2  s.co  m*/
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", Updater.USER_AGENT);

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.isEmpty()) {
            this.plugin.getLogger()
                    .warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
        this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE);
        this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE);
        this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.plugin.getLogger()
                    .severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
            this.plugin.getLogger().severe(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        this.plugin.getLogger().log(Level.SEVERE, null, e);
        return false;
    }
}

From source file:org.eclipse.rdf4j.repository.http.HTTPRepositoryConnection.java

public void add(URL url, String baseURI, RDFFormat dataFormat, Resource... contexts)
        throws IOException, RDFParseException, RepositoryException {
    if (baseURI == null) {
        baseURI = url.toExternalForm();/*w  ww  .  j av  a 2  s  . c  o  m*/
    }

    URLConnection con = url.openConnection();

    // Set appropriate Accept headers
    if (dataFormat != null) {
        for (String mimeType : dataFormat.getMIMETypes()) {
            con.addRequestProperty("Accept", mimeType);
        }
    } else {
        Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
        List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, true, null);
        for (String acceptParam : acceptParams) {
            con.addRequestProperty("Accept", acceptParam);
        }
    }

    InputStream in = con.getInputStream();

    if (dataFormat == null) {
        // Try to determine the data's MIME type
        String mimeType = con.getContentType();
        int semiColonIdx = mimeType.indexOf(';');
        if (semiColonIdx >= 0) {
            mimeType = mimeType.substring(0, semiColonIdx);
        }
        dataFormat = Rio.getParserFormatForMIMEType(mimeType).orElse(
                Rio.getParserFormatForFileName(url.getPath()).orElseThrow(Rio.unsupportedFormat(mimeType)));
    }

    try {
        add(in, baseURI, dataFormat, contexts);
    } finally {
        in.close();
    }
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

/**
 * Implement a simple proxy// w ww  .  j  ava2s . co m
 *
 * @param requestedURL the requested URL
 * @param req the HttpServletRequest
 * @return
 */
@GET
@Path("proxy")
public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL,
        @Context HttpServletRequest req) {

    BufferedReader in = null;

    try {
        URL url = new URL(requestedURL);
        URLConnection urlConnection = url.openConnection();

        int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout();

        // Set base properties
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec

        String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT);
        if (StringUtils.isNotBlank(acceptedDataFormat)) {
            urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat);
        }

        // Open the connection
        urlConnection.connect();

        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;

            int statusCode = httpConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // Follow the redirect
                String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION);
                httpConnection.disconnect();

                if (StringUtils.isNotBlank(newLocation)) {
                    return this.proxy(newLocation, req);
                } else {
                    return Response.status(statusCode).build();
                }
            } else if (statusCode == HttpURLConnection.HTTP_OK) {

                // Send the response
                StringBuilder sbf = new StringBuilder();

                // Check if the contentType is supported
                boolean contentTypeSupported = false;
                String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE);
                List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes();
                if (contentType != null) {
                    for (String cMime : supportedMimeTypes) {
                        if (contentType.equals(cMime) || contentType.contains(cMime)) {
                            contentTypeSupported = true;
                            break;
                        }
                    }
                }

                if (!contentTypeSupported) {
                    httpConnection.disconnect();
                    return Response.status(Status.NOT_ACCEPTABLE).build();
                }

                String contentEncoding = httpConnection.getContentEncoding();
                if (StringUtils.isBlank(contentEncoding)) {
                    contentEncoding = "UTF-8";
                }

                InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(),
                        Charset.forName(contentEncoding));
                in = new BufferedReader(inStrem);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sbf.append(inputLine);
                    sbf.append("\r\n");
                }

                in.close();
                httpConnection.disconnect();

                return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType)
                        .entity(sbf.toString()).build();

            } else {
                httpConnection.disconnect();
                return Response.status(statusCode).build();
            }
        }

        return Response.status(Status.BAD_REQUEST).build();

    } catch (MalformedURLException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.BAD_REQUEST).build();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
}

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private HttpURLConnection connect(String suffix) throws IOException {
    log.debug("getting " + suffix);
    URL url = new URL(seek, suffix);
    URLConnection conn;
    if (proxy == null)
        conn = url.openConnection();/*from  ww  w .  j  a  va  2s .  c o  m*/
    else {
        conn = url.openConnection(proxy);
        log.debug("used proxy configuration " + proxy);
    }
    if (credentials != null) {
        conn.addRequestProperty("Authorization", credentials);
        log.debug("added SEEK credentials to request context");
    }
    return (HttpURLConnection) conn;
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest.java

@Test
public void testGetBookAsArray() throws Exception {
    URL url = new URL("http://localhost:" + PORT + "/the/bookstore/books/list/123");
    URLConnection connect = url.openConnection();
    connect.addRequestProperty("Accept", "application/json");
    InputStream in = connect.getInputStream();

    assertEquals("{\"Books\":{\"books\":[{\"id\":123,\"name\":\"CXF in Action\"}]}}",
            getStringFromInputStream(in));

}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest.java

private void getBook(String endpointAddress, String resource, String type, String mHeader) throws Exception {
    URL url = new URL(endpointAddress);
    URLConnection connect = url.openConnection();
    connect.addRequestProperty("Content-Type", "*/*");
    connect.addRequestProperty("Accept", type);
    connect.addRequestProperty("Accept-Encoding", "gzip;q=1.0, identity; q=0.5, *;q=0");
    if (mHeader != null) {
        connect.addRequestProperty("X-HTTP-Method-Override", mHeader);
    }//from   w w w  . ja v a2 s  .  co m
    InputStream in = connect.getInputStream();

    InputStream expected = getClass().getResourceAsStream(resource);
    assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
            stripXmlInstructionIfNeeded(getStringFromInputStream(in)));
}

From source file:edu.ucuenca.authorsdisambiguation.Distance.java

public synchronized String Http(String s) throws SQLException, IOException {

    Statement stmt = conn.createStatement();
    String sql;/*from w  w  w . j a  v a  2s . c  o m*/
    sql = "SELECT * FROM cache where cache.key='" + getMD5(s) + "'";
    java.sql.ResultSet rs = stmt.executeQuery(sql);
    String resp = "";
    if (rs.next()) {
        resp = rs.getString("value");
        rs.close();
        stmt.close();
    } else {
        rs.close();
        stmt.close();
        final URL url = new URL(s);
        final URLConnection connection = url.openConnection();
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
        connection.addRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

        try {
            JsonParser parser = new JsonParser();
            parser.parse(resp);
            PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)");
            stmt2.setString(1, getMD5(s));
            stmt2.setString(2, resp);
            stmt2.executeUpdate();
            stmt2.close();
        } catch (Exception e) {
            System.out.printf("Error al insertar en la DB: " + e);
        }

    }

    return resp;
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSSoapBookTest.java

private InputStream getHttpInputStream(String endpointAddress) throws Exception {
    URL url = new URL(endpointAddress);

    URLConnection connect = url.openConnection();
    connect.addRequestProperty("Accept", "application/xml,text/plain");
    return connect.getInputStream();
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSSoapBookTest.java

@Test
public void testGetAll() throws Exception {
    URL url = new URL("http://localhost:" + PORT + "/test/services/rest2/myRestService");

    URLConnection connect = url.openConnection();
    connect.addRequestProperty("Accept", "text/plain");
    InputStream in = connect.getInputStream();

    assertEquals("0", getStringFromInputStream(in));

}