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:org.apache.cayenne.rop.http.HttpROPConnector.java

protected InputStream doRequest(byte[] data) throws IOException {
    URLConnection connection = new URL(url).openConnection();

    if (readTimeout != null) {
        connection.setReadTimeout(readTimeout.intValue());
    }/*  ww  w  . ja va2 s .  co m*/

    addAuthHeader(connection);
    addSessionCookie(connection);
    connection.setDoOutput(true);

    connection.setRequestProperty("Content-Type", "application/octet-stream");

    if (data != null) {
        try (OutputStream output = connection.getOutputStream()) {
            output.write(data);
            output.flush();
        }
    }

    return connection.getInputStream();
}

From source file:org.xlrnet.metadict.engines.heinzelnisse.HeinzelnisseEngine.java

@NotNull
private URLConnection buildUrlConnection(@NotNull URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    connection.setRequestProperty("Referrer", "http://www.heinzelnisse.info/app");
    connection.setConnectTimeout(5000);// ww w  .  j a  va2s .  co m
    connection.setReadTimeout(5000);
    return connection;
}

From source file:game.Clue.JerseyClient.java

public void getAvailableSlot() {

    try {/*from   w ww. j  ava  2  s .  c  o m*/
        for (int i = 1; i < 7; i++) {
            // URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game/Status");
            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player"
                            + i + "/");
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //  while (in.readLine() != null) {
            //}
            System.out.println("\nGET Request for :" + "Get Available slot " + "Sent");

            if ((in.readLine()).contains("no name")) {
                game_slot = i;
                i = 7;
            } else {

            }
            System.out.print("You have slot # " + game_slot);
            //close connection
            in.close();
        }

    } catch (Exception e) {
        System.out.println("\nError slot taken..Checking for another open slot...");
        System.out.println(e);

    }

}

From source file:org.owasp.jbrofuzz.update.StartUpdateChecker.java

/**
 * <p>/*from w  w  w.j a va2 s.  c o  m*/
 * Static method for getting the current online version of JBroFuzz.
 * </p>
 * 
 * <p>
 * This method makes a connection to the OWASP web site, checking for the
 * latest version number.
 * </p>
 * 
 * @return double of the version or 0.0 in case of an error
 * 
 * @author subere@uncon.org
 * @version 2.5
 * @since 1.3
 */
private static double getWebsiteVersion() {

    String response = "";
    BufferedReader instream = null;

    try {

        final URL url = new URL(JBroFuzzFormat.URL_WEBSITE);
        final URLConnection urlc;

        final boolean proxyEnabled = JBroFuzz.PREFS.getBoolean(JBroFuzzPrefs.UPDATE[0].getId(), false);
        if (proxyEnabled) {

            final String proxy = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[1].getId(), "");
            final int port = JBroFuzz.PREFS.getInt(JBroFuzzPrefs.UPDATE[2].getId(), -1);
            // A note here, proxy has no http:// or https://
            Proxy myProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, port));
            urlc = url.openConnection(myProxy);
            // Username:Password, yawn

            final boolean proxyReqAuth = JBroFuzz.PREFS.getBoolean(JBroFuzzPrefs.UPDATE[3].getId(), false);
            if (proxyReqAuth) {

                final String user = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[5].getId(), "");
                final String pass = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[6].getId(), "");
                final String encodedPassword = EncoderHashCore.encode(user + ":" + pass, "Base64");
                urlc.setRequestProperty("Proxy-Authorization", "Basic " + encodedPassword);
            }

        } else {

            urlc = url.openConnection();

        }
        urlc.setRequestProperty("User-Agent", "JBroFuzz/" + JBroFuzzFormat.VERSION);

        final int statusCode = ((HttpURLConnection) urlc).getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK) {

            instream = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

            // Typically returns -1
            final long contentLength = urlc.getContentLength();

            if (contentLength > Integer.MAX_VALUE) {
                return ZERO_VERSION;
            }

            int count;
            int limit = 0;
            final StringBuffer body = new StringBuffer(Character.MAX_VALUE);
            // 
            while (((count = instream.read()) != -1) && (limit < Character.MAX_VALUE)) {
                body.append((char) count);
                limit++;
            }
            instream.close();

            response = body.toString();

        } else {
            return ZERO_VERSION;
        } // else statement for a 200 response

    } catch (final IOException e) {
        return ZERO_VERSION;
    } finally {
        IOUtils.closeQuietly(instream);
    }

    if (!response.equalsIgnoreCase("")) {

        final Pattern pattern1 = Pattern.compile("Current version is (\\d.\\d)");
        final Matcher match1 = pattern1.matcher(response);
        if (match1.find()) {
            final String webVersion = match1.group().substring(19, 22);

            try {
                // Return the value, if found
                return Double.parseDouble(webVersion);

            } catch (final NumberFormatException e) {
                // Return 0.0 if an error occurs
                return ZERO_VERSION;

            }

        } else {
            return ZERO_VERSION;
        }
    }
    return ZERO_VERSION;
}

From source file:org.wikidata.wdtk.util.WebResourceFetcherImpl.java

@Override
public InputStream getInputStreamForUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    URLConnection urlConnection = null;
    if (proxy != null) {
        //         InetSocketAddress sa = new InetSocketAddress("llproxy.llan.ll.mit.edu", 8080);
        //           Proxy proxy = new Proxy(Proxy.Type.HTTP, sa);
        urlConnection = url.openConnection(proxy);
    } else {/* ww  w.  j a v a  2 s .  c o m*/
        urlConnection = url.openConnection();
    }

    urlConnection.setRequestProperty("User-Agent", userAgent);

    return urlConnection.getInputStream();
}

From source file:org.omegat.languagetools.LanguageToolNetworkBridge.java

@Override
@SuppressWarnings("unchecked")
protected List<LanguageToolResult> getCheckResultsImpl(String sourceText, String translationText)
        throws Exception {
    if (targetLang == null) {
        return Collections.emptyList();
    }//w ww . j  a  v  a 2  s .  c om

    URL url = new URL(serverUrl);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", OStrings.getNameAndVersion());
    conn.setDoOutput(true);
    try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
        String srcLang = sourceLang == null ? null : sourceLang.toString();
        writer.write(buildPostData(srcLang, targetLang.toString(), sourceText, translationText,
                disabledCategories, disabledRules, enabledRules));
        writer.flush();
    }

    checkHttpError(conn);

    String json = "";
    try (InputStream in = conn.getInputStream()) {
        json = IOUtils.toString(in, StandardCharsets.UTF_8);
    }

    Map<String, Object> response = (Map<String, Object>) JsonParser.parse(json);
    Map<String, String> software = (Map<String, String>) response.get("software");

    if (!software.get("apiVersion").equals(API_VERSION)) {
        Log.logWarningRB("LT_API_VERSION_MISMATCH");
    }

    List<Map<String, Object>> matches = (List<Map<String, Object>>) response.get("matches");

    return matches.stream().map(match -> {
        String message = addSuggestionTags((String) match.get("message"));
        int start = (int) match.get("offset");
        int end = start + (int) match.get("length");
        Map<String, Object> rule = (Map<String, Object>) match.get("rule");
        String ruleId = (String) rule.get("id");
        String ruleDescription = (String) rule.get("description");
        return new LanguageToolResult(message, start, end, ruleId, ruleDescription);
    }).collect(Collectors.toList());
}

From source file:org.dataconservancy.dcs.ingest.services.ExternalContentStager.java

private void stageExternalFile(DcsFile file) {

    List<DcsEvent> eventsToAdd = new ArrayList<DcsEvent>();

    URL fileUrl;//from w ww  . j a  va 2  s .co m
    try {
        fileUrl = new URL(encodeTagId(file.getSource()));
    } catch (MalformedURLException e) {
        throw new RuntimeException(
                String.format("Invalid file content url in file %s: %s", file.getId(), file.getSource()));
    }

    HashMap<String, String> metadata = new HashMap<String, String>();

    if (file.getName() == null) {
        file.setName(getFileName(fileUrl));
    }

    /* Stage the content */
    InputStream stream = null;
    StagedFile staged = null;
    try {
        InputStream src = null;
        if (file.getSource().contains("file:"))
            src = fileUrl.openStream();
        else if (file.getSource().contains("http:") || file.getSource().contains("https:")) {
            String loginPassword = this.acrUser + ":" + this.acrPassword;
            String encoded = new sun.misc.BASE64Encoder().encode(loginPassword.getBytes());
            URLConnection conn = fileUrl.openConnection();
            conn.setConnectTimeout(15 * 1000);
            conn.setReadTimeout(15 * 1000);
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            src = conn.getInputStream();
        }
        stream = fixityFilter(src, metadata, eventsToAdd);
        staged = ingest.getFileContentStager().add(stream, metadata);
        // file.setSource(staged.getReferenceURI());
        // TODO : Directly setting the access URI due to Reference URI resolving issues for large collections
        file.setSource(staged.getAccessURI());
    } catch (IOException e) {
        throw new RuntimeException("Error getting content from " + fileUrl.toString());
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                log.error("Error while downloading file", e);
            }
        }
    }

    /*
     * Add digest and download events to the staged content's sip, as well
     * as fixity values themselves
     */
    updateStagedSip(staged.getSipRef(), fileUrl, metadata, eventsToAdd);

}

From source file:net.hockeyapp.android.internal.CheckUpdateTask.java

protected URLConnection createConnection(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("User-Agent", "Hockey/Android");
    connection.setRequestProperty("connection", "close");
    return connection;
}

From source file:game.Clue.JerseyClient.java

public JerseyClient() {

    String string = "";

    try {/*from w ww .  j av a 2s .c om*/
        //System.out.println("jerseyclient started");
        currentgame_state = new JSONObject(
                "{\"players\":[{\"position\":\"0,3\",\"name\":null,\"active\":\"true\",\"cards\":\"MR GREEN,CANDLESTICK,BALLROOM\",\"character\":\"scarlet\"},{\"position\":\"1,4\",\"name\":null,\"active\":\"true\",\"cards\":\"PROFESSOR PLUM,BILLARD ROOM,ROPE\",\"character\":\"mustard\"},{\"position\":\"4,3\",\"name\":null,\"active\":\"true\",\"cards\":\"DINING ROOM,REVOLVER,WRENCH\",\"character\":\"white\"},{\"position\":\"4,1\",\"name\":null,\"active\":\"true\",\"cards\":\"LIBRARY,COLONEL MUSTARD,STUDY\",\"character\":\"green\"},{\"position\":\"3,0\",\"name\":null,\"active\":\"true\",\"cards\":\"MISS SCARLET,MRS PEACOCK,KNIFE\",\"character\":\"peacock\"},{\"position\":\"1,0\",\"name\":null,\"active\":\"true\",\"cards\":\"HALL,CONSERVATORY,LOUNGE\",\"character\":\"plum\"}],\"move_state\":{\"player\":\"scarlet\",\"moves\":[[\"[0,4], [0,2]\",\"accusation\"]]},\"winner\":null}\"))");

        String username = "Mario";
        // Step1: Let's 1st read file from fileSystem
        InputStream crunchifyInputStream = new FileInputStream(
                "/Users/" + username + "/Documents/JsonTest/JSONFile.txt");
        InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream);
        BufferedReader br = new BufferedReader(crunchifyReader);
        String line;
        while ((line = br.readLine()) != null) {
            string += line + "\n";
        }

        JSONObject jsonObject = new JSONObject(string);
        //System.out.println(jsonObject);

        // Step2: Now get JSON File Data from REST Service
        try {

            JsonParser Parser;
            //URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game");
            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game");
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //  while (in.readLine() != null) {
            //}
            System.out.print(in.readLine());
            System.out.println("\nREST Service Invoked Successfully..GET Request Sent");
            //getGameState();

            // sendPUT(ClueGameUI.jTextField2.getText());
            //send JSON to Parser
            //Parser=new JsonParser(in.readLine());
            //System.out.println("Parser called");
            // sendPUT();
            //close connection
            in.close();

        } catch (Exception e) {
            System.out.println("\nError while calling REST Service");
            System.out.println(e);
        }

        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.jetoile.hadoopunit.integrationtest.ManualIntegrationBootstrapTest.java

@Test
public void hdfsShouldStart() throws Exception {

    //        assertThat(Utils.available("127.0.0.1", configuration.getInt(Config.HDFS_NAMENODE_HTTP_PORT_KEY))).isFalse();
    ////from   w ww  .  j  a  v  a  2  s. co  m
    //        org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
    //        conf.set("fs.default.name", "hdfs://127.0.0.1:" + configuration.getInt(Config.HDFS_NAMENODE_PORT_KEY));
    //
    //        URI uri = URI.create ("hdfs://127.0.0.1:" + configuration.getInt(Config.HDFS_NAMENODE_PORT_KEY));
    //
    //        FileSystem hdfsFsHandle = FileSystem.get (uri, conf);
    FileSystem hdfsFsHandle = HdfsUtils.INSTANCE.getFileSystem();

    FSDataOutputStream writer = hdfsFsHandle
            .create(new Path(configuration.getString(HadoopUnitConfig.HDFS_TEST_FILE_KEY)));
    writer.writeUTF(configuration.getString(HadoopUnitConfig.HDFS_TEST_STRING_KEY));
    writer.close();

    // Read the file and compare to test string
    FSDataInputStream reader = hdfsFsHandle
            .open(new Path(configuration.getString(HadoopUnitConfig.HDFS_TEST_FILE_KEY)));
    assertEquals(reader.readUTF(), configuration.getString(HadoopUnitConfig.HDFS_TEST_STRING_KEY));
    reader.close();
    hdfsFsHandle.close();

    URL url = new URL(String.format("http://localhost:%s/webhdfs/v1?op=GETHOMEDIRECTORY&user.name=guest",
            configuration.getInt(HadoopUnitConfig.HDFS_NAMENODE_HTTP_PORT_KEY)));
    URLConnection connection = url.openConnection();
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    BufferedReader response = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = response.readLine();
    response.close();
    assertThat("{\"Path\":\"/user/guest\"}").isEqualTo(line);

}