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:test.security.ClassSecurityTest.java

public void testAccessDeniedBasicAuthenticationGetXML() throws Exception {
    Class cashKlass = Cash.class;

    if (enableCaGridLoginModule) {
        return;/*  w  w w  . j a  v  a2 s  .  co  m*/
    }

    try {
        String searchUrl = getServerURL() + "/GetXML?query=" + cashKlass.getName() + "&" + cashKlass.getName();
        URL url = new URL(searchUrl);
        URLConnection conn = url.openConnection();

        //String base64 = "/O=caBIG/OU=caGrid/OU=Training/OU=Dorian/CN=SDKUser2" + ":" + "Psat123!@#"; //user2 does not have access to the Cash class
        String base64 = "SKUser2" + ":" + "Psat123!@#"; //user2 does not have access to the Cash class
        conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        File myFile = new File(cashKlass.getName() + "_test-getxml.xml");

        FileWriter myWriter = new FileWriter(myFile);
        DataInputStream dis = new DataInputStream(conn.getInputStream());

        String s, buffer = "";
        while ((s = (dis.readLine())) != null) {
            myWriter.write(s);
            buffer = buffer + s;
        }

        myWriter.close();

        assertTrue(buffer.indexOf("Access is denied") > 0);
        myFile.delete();

    } catch (Exception e) {
        System.out.println("Exception caught: " + e.getMessage());
        assertTrue(e.getMessage().indexOf("401") > 0); //Server returned HTTP response code: 401
        //fail(e.getMessage());
    }
}

From source file:com.spinn3r.api.BaseClient.java

protected URLConnection getConnection(String resource) throws IOException {

    URLConnection conn = null;

    try {//from  w ww .j a va 2s  .  com

        // create the HTTP connection.
        URL request = new URL(resource);
        conn = request.openConnection();

        // set the UserAgent so Spinn3r know which client lib is calling.
        conn.setRequestProperty(USER_AGENT_HEADER, USER_AGENT + "; " + getConfig().getCommandLine());
        conn.setRequestProperty(ACCEPT_ENCODING_HEADER, GZIP_ENCODING);
        conn.setConnectTimeout(20000);
        conn.connect();

    }

    catch (IOException ioe) {

        //create a custom exception message with the right error.
        String message = conn.getHeaderField(null);
        IOException ce = new IOException(message);
        ce.setStackTrace(ioe.getStackTrace());

        throw ce;
    }

    return conn;
}

From source file:net.longfalcon.newsj.TVRageService.java

public void rebuildTvInfo(TvRage tvRage) {
    try {/* w  ww .  j  a  va 2s. c o  m*/
        TraktResult traktResult = getTraktMatch(tvRage.getReleaseTitle());
        if (traktResult != null) {
            TraktShowResult showResult = traktResult.getShowResult();

            _log.info("found tvinfo for " + tvRage.getReleaseTitle());

            tvRage.setTraktId(showResult.getIds().getTrakt());
            tvRage.setRageId(showResult.getIds().getTvrage());
            tvRage.setTvdbId(showResult.getIds().getTvdb());
            tvRage.setReleaseTitle(showResult.getTitle());
            TraktImages traktImages = showResult.getTraktImages();
            try {
                if (traktImages != null) {
                    TraktImage posterImage = traktImages.getPoster();
                    if (posterImage != null) {
                        String posterUrl = posterImage.getMedium();
                        if (ValidatorUtil.isNotNull(posterUrl)) {
                            Directory tempDir = fileSystemService.getDirectory("/temp");
                            File tempFile = tempDir
                                    .getTempFile("image_" + String.valueOf(System.currentTimeMillis()));
                            FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
                            URL url = new URL(posterUrl);
                            URLConnection urlConnection = url.openConnection();
                            urlConnection.setRequestProperty("User-Agent", "Java");
                            StreamUtil.transferByteArray(urlConnection.getInputStream(), fileOutputStream,
                                    1024);
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            InputStream tempFileInputStream = new FileInputStream(tempFile);
                            StreamUtil.transferByteArray(tempFileInputStream, byteArrayOutputStream, 1024);
                            tvRage.setImgData(byteArrayOutputStream.toByteArray());
                        }
                    }
                }
            } catch (Exception e) {
                _log.warn("unable to add poster image for " + tvRage.getReleaseTitle(), e);
            }

            tvRage.setDescription(showResult.getOverview());
            tvRageDAO.update(tvRage);
        }
    } catch (Exception e) {
        _log.error(e);
    }
}

From source file:org.opennms.xmlclient.BasicHttpMethods.java

/**
 * Sends an HTTP GET request to a url// w  w  w  .  ja v  a2  s.co m
 *
 * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
 * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
 * @return - The response from the end point
 */
public String sendGetRequest(String endpoint, String requestParameters, String username, String password)
        throws Exception {
    String result = null;
    if (endpoint.startsWith("http://")) {
        // Send a GET request to the servlet
        try {
            // Send data
            String urlStr = endpoint;
            if (requestParameters != null && requestParameters.length() > 0) {
                urlStr += "?" + requestParameters;
            }
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();

            // set username and password 
            // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
            String userPassword = username + ":" + password;
            // Encode String
            // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
            byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
            String authStringEnc = new String(encoding);
            log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
            conn.setRequestProperty("Authorization", "Basic " + authStringEnc);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            result = sb.toString();

        } catch (Throwable e) {
            throw new Exception("problem issuing get to URL", e);
        }
    }
    return result;
}

From source file:org.ixdhof.speechrecognizer.Recognizer.java

private void do_recognize(String waveString, String language) throws Exception {
    //"en-US"// w w w . j  a v a  2  s . co m

    URL url;
    URLConnection urlConn;
    OutputStream outputStream;
    BufferedReader br;

    File waveFile = new File(parent.sketchPath(waveString));

    FlacEncoder flacEncoder = new FlacEncoder();
    File flacFile = new File(waveFile + ".flac");

    flacEncoder.convertWaveToFlac(waveFile, flacFile);

    // URL of Remote Script.
    url = new URL(GOOGLE_RECOGNIZER_URL_NO_LANG + language);

    // Open New URL connection channel.
    urlConn = url.openConnection();

    // we want to do output.
    urlConn.setDoOutput(true);

    // No caching
    urlConn.setUseCaches(false);

    // Specify the header content type.
    urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");

    // Send POST output.
    outputStream = urlConn.getOutputStream();

    FileInputStream fileInputStream = new FileInputStream(flacFile.getAbsolutePath());

    byte[] buffer = new byte[256];

    while ((fileInputStream.read(buffer, 0, 256)) != -1) {
        outputStream.write(buffer, 0, 256);
    }

    fileInputStream.close();
    outputStream.close();

    // Get response data.
    br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

    response = br.readLine();

    br.close();

    flacFile.delete();
    waveFile.delete();

    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(response);
        JSONObject jsonObject = (JSONObject) obj;
        HashMap returnValues = new HashMap();

        if (response.contains("utterance")) {
            status = (int) (long) (Long) jsonObject.get("status");
            id = (String) jsonObject.get("id");
            JSONArray hypotheses_array = (JSONArray) jsonObject.get("hypotheses");
            JSONObject hypotheses = (JSONObject) hypotheses_array.get(0);
            utterance = (String) hypotheses.get("utterance");
            confidence = (float) (double) (Double) hypotheses.get("confidence");
        } else {
            utterance = null;
        }

        if (recognizerEvent != null) {
            try {
                recognizerEvent.invoke(parent, new Object[] { utterance });
            } catch (Exception e) {
                System.err.println("Disabling recognizerEvent()");
                e.printStackTrace();
                recognizerEvent = null;
            }
        }
    } catch (Exception e) {
        parent.println(e);
    }

    recognizing = false;
}

From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java

/**
 * @param url not null//  w ww  .ja va2s. c o m
 * @param project not null
 * @param settings not null
 * @return the url connection with auth if required. Don't check the certificate if SSL scheme.
 * @throws IOException if any
 */
private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings)
        throws IOException {
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(TIMEOUT);
    conn.setReadTimeout(TIMEOUT);

    // conn authorization
    if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null
            && project.getDistributionManagement() != null
            && (project.getDistributionManagement().getRepository() != null
                    || project.getDistributionManagement().getSnapshotRepository() != null)
            && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl())
                    || StringUtils.isNotEmpty(
                            project.getDistributionManagement().getSnapshotRepository().getUrl()))) {
        Server server = null;
        if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getRepository().getId());
        }
        if (server == null && url.toString()
                .contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) {
            server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId());
        }

        if (server != null && StringUtils.isNotEmpty(server.getUsername())
                && StringUtils.isNotEmpty(server.getPassword())) {
            String up = server.getUsername().trim() + ":" + server.getPassword().trim();
            String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim();

            conn.setRequestProperty("Authorization", "Basic " + upEncoded);
        }
    }

    if (conn instanceof HttpsURLConnection) {
        HostnameVerifier hostnameverifier = new HostnameVerifier() {
            /** {@inheritDoc} */
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier);

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            /** {@inheritDoc} */
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            /** {@inheritDoc} */
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        } catch (NoSuchAlgorithmException e1) {
            // ignore
        } catch (KeyManagementException e) {
            // ignore
        }
    }

    return conn;
}

From source file:grafix.basedados.Download.java

public String baixaString() {
    String retorno = null;// w w  w.ja  v a2 s .  c  om
    URL url = null;
    URLConnection con = null;
    try {
        url = new URL(this.url);
        con = url.openConnection();
    } catch (Exception ex) {
        ex.printStackTrace();
        return retorno;
    }
    if (this.usaProxy) {
        System.setProperty("http.proxySet", "true");
        System.setProperty("http.proxyHost", this.servidorProxy);
        System.setProperty("http.proxyPort", String.format("%d", this.portaProxy));
        System.setProperty("http.proxyType", "4");
        if (this.usuarioProxy != null) {
            if (this.usuarioProxy.length() > 0) {
                String proxyUser = this.usuarioProxy, proxyPassword = this.senhaProxy;
                con.setRequestProperty("Proxy-Authorization",
                        "Basic " + Base64.encodeToString((proxyUser + ":" + proxyPassword).getBytes(), false));
            }
        }
    }
    try {
        int len = con.getContentLength();
        byte[] b = new byte[len];
        InputStream is = con.getInputStream();
        is.read(b, 0, len);

        String s = new String(b);
        return s;

    } catch (MalformedURLException ex) {
        System.out.println("Erro");
        return "";
    } catch (IOException ex) {
        System.out.println("Erro");
        System.out.println(ex);
        return "";
    }

}

From source file:net.solarnetwork.node.support.HttpClientSupport.java

/**
 * Get a URLConnection for a specific URL and HTTP method.
 * /*from ww  w.  j  a  v  a2  s  .com*/
 * <p>
 * If the httpMethod equals {@code POST} then the connection's
 * {@code doOutput} property will be set to <em>true</em>, otherwise it will
 * be set to <em>false</em>. The {@code doInput} property is always set to
 * <em>true</em>.
 * </p>
 * 
 * <p>
 * This method also sets up the request property
 * {@code Accept-Encoding: gzip,deflate} so the response can be compressed.
 * The {@link #getInputSourceFromURLConnection(URLConnection)} automatically
 * handles compressed responses.
 * </p>
 * 
 * <p>
 * If the {@link #getSslService()} property is configured and the URL
 * represents an HTTPS connection, then that factory will be used to for the
 * connection.
 * </p>
 * 
 * @param url
 *        the URL to connect to
 * @param httpMethod
 *        the HTTP method
 * @param accept
 *        the HTTP Accept header value
 * @return the URLConnection
 * @throws IOException
 *         if any IO error occurs
 */
protected URLConnection getURLConnection(String url, String httpMethod, String accept) throws IOException {
    URL connUrl = new URL(url);
    URLConnection conn = connUrl.openConnection();
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection hConn = (HttpURLConnection) conn;
        hConn.setRequestMethod(httpMethod);
    }
    if (sslService != null && conn instanceof HttpsURLConnection) {
        SSLService service = sslService.service();
        if (service != null) {
            SSLSocketFactory factory = service.getSolarInSocketFactory();
            if (factory != null) {
                HttpsURLConnection hConn = (HttpsURLConnection) conn;
                hConn.setSSLSocketFactory(factory);
            }
        }
    }
    conn.setRequestProperty("Accept", accept);
    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
    conn.setDoInput(true);
    conn.setDoOutput(HTTP_METHOD_POST.equalsIgnoreCase(httpMethod));
    conn.setConnectTimeout(this.connectionTimeout);
    conn.setReadTimeout(connectionTimeout);
    return conn;
}

From source file:grafix.basedados.Download.java

public String baixaArquivoGZIP() {
    String retorno = null;/*from ww w .  java  2s.  c  om*/
    URL url = null;
    URLConnection con = null;
    try {
        url = new URL(this.url);
        con = url.openConnection();
    } catch (Exception ex) {
        ex.printStackTrace();
        return retorno;
    }
    if (this.usaProxy) {
        System.setProperty("http.proxySet", "true");
        System.setProperty("http.proxyHost", this.servidorProxy);
        System.setProperty("http.proxyPort", String.format("%d", this.portaProxy));
        System.setProperty("http.proxyType", "4");
        if (this.usuarioProxy != null) {
            if (this.usuarioProxy.length() > 0) {
                String proxyUser = this.usuarioProxy, proxyPassword = this.senhaProxy;
                con.setRequestProperty("Proxy-Authorization",
                        "Basic " + Base64.encodeToString((proxyUser + ":" + proxyPassword).getBytes(), false));
            }
        }
    }
    GZIPInputStream gzip;
    try {
        gzip = new GZIPInputStream(con.getInputStream());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int readLen = 0;
        byte[] buffer = new byte[4096];
        int bytes = 0;
        //  int sfs =   gzip.      //con.getInputStream().available();
        int total = con.getContentLength();
        if (this.mostraProgresso)
            this.formAtualizacao.definirPercentualProgresso(0);
        while ((readLen = gzip.read(buffer, 0, buffer.length)) > 0) {
            os.write(buffer, 0, readLen);
            //  int sfs =  con.getInputStream().available();
            bytes += readLen;
            if (this.mostraProgresso)
                this.formAtualizacao.informaBytesLidos(bytes);
            // float sd = (float)(total-sfs)/(float)total*100.0f;
            // this.formAtualizacao.informarLog("Baixados" + (total - sfs) + " bytes de " + total + "progresso " + (int) sd);
            // this.formAtualizacao.definirPercentualProgresso( (int) sd);
        }
        retorno = os.toString();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return retorno;
}

From source file:org.apache.xml.security.utils.resolver.implementations.ResolverDirectHTTP.java

/**
 * Method resolve/*from w  w  w.j a  v a 2 s .  com*/
 *
 * @param uri
 * @param baseURI
 *
 * @throws ResourceResolverException
 * @return 
 * $todo$ calculate the correct URI from the attribute and the baseURI
 */
public XMLSignatureInput engineResolve(Attr uri, String baseURI) throws ResourceResolverException {
    try {
        boolean useProxy = false;
        String proxyHost = engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]);
        String proxyPort = engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]);

        if ((proxyHost != null) && (proxyPort != null)) {
            useProxy = true;
        }

        String oldProxySet = null;
        String oldProxyHost = null;
        String oldProxyPort = null;
        // switch on proxy usage
        if (useProxy) {
            if (log.isDebugEnabled()) {
                log.debug("Use of HTTP proxy enabled: " + proxyHost + ":" + proxyPort);
            }
            oldProxySet = System.getProperty("http.proxySet");
            oldProxyHost = System.getProperty("http.proxyHost");
            oldProxyPort = System.getProperty("http.proxyPort");
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
        }

        boolean switchBackProxy = ((oldProxySet != null) && (oldProxyHost != null) && (oldProxyPort != null));

        // calculate new URI
        URI uriNew = null;
        try {
            uriNew = getNewURI(uri.getNodeValue(), baseURI);
        } catch (URISyntaxException ex) {
            throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
        }

        URL url = uriNew.toURL();
        URLConnection urlConnection = url.openConnection();

        {
            // set proxy pass
            String proxyUser = engineGetProperty(
                    ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]);
            String proxyPass = engineGetProperty(
                    ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]);

            if ((proxyUser != null) && (proxyPass != null)) {
                String password = proxyUser + ":" + proxyPass;
                String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));

                // or was it Proxy-Authenticate ?
                urlConnection.setRequestProperty("Proxy-Authorization", encodedPassword);
            }
        }

        {
            // check if Basic authentication is required
            String auth = urlConnection.getHeaderField("WWW-Authenticate");

            if (auth != null && auth.startsWith("Basic")) {
                // do http basic authentication
                String user = engineGetProperty(
                        ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]);
                String pass = engineGetProperty(
                        ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]);

                if ((user != null) && (pass != null)) {
                    urlConnection = url.openConnection();

                    String password = user + ":" + pass;
                    String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));

                    // set authentication property in the http header
                    urlConnection.setRequestProperty("Authorization", "Basic " + encodedPassword);
                }
            }
        }

        String mimeType = urlConnection.getHeaderField("Content-Type");
        InputStream inputStream = urlConnection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buf[] = new byte[4096];
        int read = 0;
        int summarized = 0;

        while ((read = inputStream.read(buf)) >= 0) {
            baos.write(buf, 0, read);
            summarized += read;
        }

        if (log.isDebugEnabled()) {
            log.debug("Fetched " + summarized + " bytes from URI " + uriNew.toString());
        }

        XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());

        result.setSourceURI(uriNew.toString());
        result.setMIMEType(mimeType);

        // switch off proxy usage
        if (useProxy && switchBackProxy) {
            System.setProperty("http.proxySet", oldProxySet);
            System.setProperty("http.proxyHost", oldProxyHost);
            System.setProperty("http.proxyPort", oldProxyPort);
        }

        return result;
    } catch (MalformedURLException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
    } catch (IOException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, baseURI);
    }
}