Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

In this page you can find the example usage for java.net HttpURLConnection setInstanceFollowRedirects.

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Usage

From source file:piuk.blockchain.android.ui.dialogs.TransactionSummaryDialog.java

private static String fetchURL(String URL) throws Exception {
    URL url = new URL(URL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    try {//  ww w  .  j a v  a 2  s. com
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestMethod("GET");

        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);

        connection.setInstanceFollowRedirects(false);

        connection.connect();

        if (connection.getResponseCode() == 200)
            return IOUtils.toString(connection.getInputStream(), "UTF-8");
        else if (connection.getResponseCode() == 500
                && (connection.getContentType() == null || connection.getContentType().equals("text/plain")))
            throw new Exception("Error From Server: " + IOUtils.toString(connection.getErrorStream(), "UTF-8"));
        else
            throw new Exception("Unknown response from server");

    } finally {
        connection.disconnect();
    }
}

From source file:org.dcm4che3.tool.qidors.QidoRS.java

private static String sendRequest(URL url, final QidoRS main) throws IOException {

    LOG.info("URL: {}", url);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setDoOutput(true);/*from  w  w  w.j  a v  a 2 s.c  o  m*/

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(false);

    connection.setRequestMethod("GET");

    connection.setRequestProperty("charset", "utf-8");

    if (main.isJSON) {
        connection.setRequestProperty("Accept", "application/json");
    }

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);

    String response = "Server responded with " + connection.getResponseCode() + " - "
            + connection.getResponseMessage();

    InputStream in = connection.getInputStream();
    try {
        main.parserType.readBody(main, in);
    } catch (Exception e) {
        System.out.println("Error parsing Server response - " + e);
    }
    connection.disconnect();

    return response;

}

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

private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException {
    c.setInstanceFollowRedirects(false);
    c.setDoOutput(true);/*from   w  w w. j av a  2  s  .  c  o  m*/
    c.setRequestMethod("POST");
    c.setRequestProperty("Content-Type", form.contentType());
    c.setRequestProperty("Content-Length", form.length());
    c.connect();
    try (OutputStream os = c.getOutputStream()) {
        os.write(form.content());
    }
    return fromStatusCode(c.getResponseCode());
}

From source file:org.dcm4che3.tool.wadors.WadoRS.java

private static SimpleHTTPResponse sendRequest(final WadoRS main) throws IOException {
    URL newUrl = new URL(main.getUrl());

    LOG.info("WADO-RS URL: {}", newUrl);

    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();

    connection.setDoOutput(true);/*from   ww  w.j a  va 2  s.  co m*/

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(false);

    connection.setRequestMethod("GET");

    connection.setRequestProperty("charset", "utf-8");

    String[] acceptHeaders = compileAcceptHeader(main.acceptTypes);

    LOG.info("Accept-Headers: {}", Arrays.toString(acceptHeaders));

    for (String acceptStr : acceptHeaders)
        connection.addRequestProperty("Accept", acceptStr);

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);

    int responseCode = connection.getResponseCode();
    String responseMessage = connection.getResponseMessage();

    boolean isErrorCase = responseCode >= HttpURLConnection.HTTP_BAD_REQUEST;
    if (!isErrorCase) {

        InputStream in = null;
        if (connection.getHeaderField("content-type").contains("application/json")
                || connection.getHeaderField("content-type").contains("application/zip")) {
            String headerPath;
            in = connection.getInputStream();
            if (main.dumpHeader)
                headerPath = writeHeader(connection.getHeaderFields(),
                        new File(main.outDir, "out.json" + "-head"));
            else {
                headerPath = connection.getHeaderField("content-location");
            }
            File f = new File(main.outDir,
                    connection.getHeaderField("content-type").contains("application/json") ? "out.json"
                            : "out.zip");
            Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
            main.retrievedInstances.put(headerPath, f.toPath().toAbsolutePath());
        } else {
            if (main.dumpHeader)
                dumpHeader(main, connection.getHeaderFields());
            in = connection.getInputStream();
            try {
                File spool = new File(main.outDir, "Spool");
                Files.copy(in, spool.toPath(), StandardCopyOption.REPLACE_EXISTING);
                String boundary;
                BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(spool)));
                boundary = (rdr.readLine());
                boundary = boundary.substring(2, boundary.length());
                rdr.close();
                FileInputStream fin = new FileInputStream(spool);
                new MultipartParser(boundary).parse(fin, new MultipartParser.Handler() {

                    @Override
                    public void bodyPart(int partNumber, MultipartInputStream partIn) throws IOException {

                        Map<String, List<String>> headerParams = partIn.readHeaderParams();
                        String mediaType;
                        String contentType = headerParams.get("content-type").get(0);

                        if (contentType.contains("transfer-syntax"))
                            mediaType = contentType.split(";")[0];
                        else
                            mediaType = contentType;

                        // choose writer
                        if (main.isMetadata) {
                            main.writerType = ResponseWriter.XML;

                        } else {
                            if (mediaType.equalsIgnoreCase("application/dicom")) {
                                main.writerType = ResponseWriter.DICOM;
                            } else if (isBulkMediaType(mediaType)) {
                                main.writerType = ResponseWriter.BULK;
                            } else {
                                throw new IllegalArgumentException("Unknown media type "
                                        + "returned by server, media type = " + mediaType);
                            }

                        }
                        try {
                            main.writerType.readBody(main, partIn, headerParams);
                        } catch (Exception e) {
                            System.out.println("Error parsing media type to determine extension" + e);
                        }
                    }

                    private boolean isBulkMediaType(String mediaType) {
                        if (mediaType.contains("octet-stream"))
                            return true;
                        for (Field field : MediaTypes.class.getFields()) {
                            try {
                                if (field.getType().equals(String.class)) {
                                    String tmp = (String) field.get(field);
                                    if (tmp.equalsIgnoreCase(mediaType))
                                        return true;
                                }
                            } catch (Exception e) {
                                System.out.println("Error deciding media type " + e);
                            }
                        }

                        return false;
                    }
                });
                fin.close();
                spool.delete();
            } catch (Exception e) {
                System.out.println("Error parsing Server response - " + e);
            }
        }

    } else {
        LOG.error("Server returned {} - {}", responseCode, responseMessage);
    }

    connection.disconnect();

    main.response = new WadoRSResponse(responseCode, responseMessage, main.retrievedInstances);
    return new SimpleHTTPResponse(responseCode, responseMessage);

}

From source file:org.dcm4che3.tool.wadouri.WadoURI.java

private static String sendRequest(final WadoURI main) throws Exception {
    URL newUrl = new URL(setWadoRequestQueryParams(main, main.getUrl()));
    System.out.println(newUrl.toString());
    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();

    connection.setDoOutput(true);/*from   www. jav a2s  .c om*/

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(true);

    connection.setRequestMethod("GET");

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);
    String response = "Server responded with " + connection.getResponseCode() + " - "
            + connection.getResponseMessage();
    InputStream in = connection.getInputStream();

    String contentType = connection.getHeaderField("Content-Type");

    if (contentType.contains("application")) {
        if (contentType.contains("application/dicom+xml"))
            writeXML(in, main);
        else if (contentType.contains("application/pdf"))
            writeFile(in, main, ".pdf");
        else //dicom 
            writeFile(in, main, ".dcm");
    } else if (contentType.contains("image")) {
        if (contentType.contains("image/jpeg"))
            writeFile(in, main, ".jpeg");
        else if (contentType.contains("image/png"))
            writeFile(in, main, ".png");
        else //gif
            writeFile(in, main, ".gif");
    } else if (contentType.contains("text")) {
        if (contentType.contains("text/html")) {
            writeFile(in, main, ".html");
        } else if (contentType.contains("text/rtf")) {
            writeFile(in, main, ".rtf");
        } else // text/plain
            writeFile(in, main, ".txt");
    }
    connection.disconnect();

    return response;

}

From source file:org.bibsonomy.util.WebUtils.java

/**
 * Sends a request to the given URL and checks, if it contains a redirect.
 * If it does, returns the redirect URL. Otherwise, returns null.
 * This is done up to {@value #MAX_REDIRECT_COUNT}-times until the final page is reached. 
 *  //from   ww w. ja  v a2 s  . c  o  m
 * 
 * 
 * @param url
 * @return - The redirect URL.
 */
public static URL getRedirectUrl(final URL url) {
    try {
        URL internalUrl = url;
        URL previousUrl = null;
        int redirectCtr = 0;
        while (internalUrl != null && redirectCtr < MAX_REDIRECT_COUNT) {
            redirectCtr++;

            final HttpURLConnection urlConn = (HttpURLConnection) internalUrl.openConnection();

            urlConn.setAllowUserInteraction(false);
            urlConn.setDoInput(true);
            urlConn.setDoOutput(false);
            urlConn.setUseCaches(false);
            urlConn.setInstanceFollowRedirects(false);

            /*
             * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some 
             * pages require it to download content.
             */
            urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE);

            urlConn.connect();

            // get URL to redirected resource
            previousUrl = internalUrl;
            try {
                internalUrl = new URL(urlConn.getHeaderField(LOCATION));
            } catch (final MalformedURLException e) {
                internalUrl = null;
            }

            urlConn.disconnect();

        }

        return previousUrl;
    } catch (final IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.chiorichan.util.WebUtils.java

/**
 * Establishes an HttpURLConnection from a URL, with the correct configuration to receive content from the given URL.
 * /* w  ww  . j  av  a2s. c  om*/
 * @param url
 *            The URL to set up and receive content from
 * @return A valid HttpURLConnection
 * 
 * @throws IOException
 *             The openConnection() method throws an IOException and the calling method is responsible for handling it.
 */
public static HttpURLConnection openHttpConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(false);
    System.setProperty("http.agent", getUserAgent());
    conn.setRequestProperty("User-Agent", getUserAgent());
    HttpURLConnection.setFollowRedirects(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    return conn;
}

From source file:org.apache.hadoop.hdfs.web.WebHdfsFileSystem.java

/**
 * Two-step Create/Append:// ww w . j ava2 s .co m
 * Step 1) Submit a Http request with neither auto-redirect nor data. 
 * Step 2) Submit another Http request with the URL from the Location header with data.
 * 
 * The reason of having two-step create/append is for preventing clients to
 * send out the data before the redirect. This issue is addressed by the
 * "Expect: 100-continue" header in HTTP/1.1; see RFC 2616, Section 8.2.3.
 * Unfortunately, there are software library bugs (e.g. Jetty 6 http server
 * and Java 6 http client), which do not correctly implement "Expect:
 * 100-continue". The two-step create/append is a temporary workaround for
 * the software library bugs.
 */
static HttpURLConnection twoStepWrite(HttpURLConnection conn, final HttpOpParam.Op op) throws IOException {
    //Step 1) Submit a Http request with neither auto-redirect nor data. 
    conn.setInstanceFollowRedirects(false);
    conn.setDoOutput(false);
    conn.connect();
    validateResponse(HttpOpParam.TemporaryRedirectOp.valueOf(op), conn);
    final String redirect = conn.getHeaderField("Location");
    conn.disconnect();

    //Step 2) Submit another Http request with the URL from the Location header with data.
    conn = (HttpURLConnection) new URL(redirect).openConnection();
    conn.setRequestMethod(op.getType().toString());
    return conn;
}

From source file:org.dcm4che3.tool.qc.QC.java

private static QCResult sendRequest(String desc, QC qc, Object qcMessage) {

    HttpURLConnection connection = null;
    String bfr = "";
    QCResult result = null;//from w w w  .j a v  a2  s.c  o m
    try {
        URL url = new URL(qc.getUrl());
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);

        connection.setDoInput(true);

        connection.setInstanceFollowRedirects(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Accept", "application/json");

        connection.setUseCaches(false);

        writeMessage(connection, (JsonStructure) qcMessage);

        InputStream in = connection.getInputStream();

        BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
        while (rdr.ready())
            bfr += rdr.readLine();
        result = new QCResult(desc, bfr, connection.getResponseCode());
        return result;
    } catch (Exception e) {
        System.out.println("Error preparing request or " + "parsing Server response - " + e);
    }
    connection.disconnect();
    return result;
}

From source file:org.dcm4che3.tool.qc.QC.java

private static QCResult sendDeleteRequest(String desc, QC qc) {
    HttpURLConnection connection = null;
    String bfr = "";
    QCResult result = null;// ww  w. j a  va2 s .co  m
    try {
        URL url = new URL(adjustDeleteURL(qc).replace(" ", "%20"));
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);

        connection.setDoInput(true);

        connection.setInstanceFollowRedirects(false);

        connection.setRequestMethod("DELETE");

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream in = connection.getInputStream();

            BufferedReader rdr = new BufferedReader(new InputStreamReader(in));

            while (rdr.ready())
                bfr += rdr.readLine();
        }
        result = new QCResult(desc, bfr, responseCode);
        return result;
    } catch (Exception e) {
        System.out.println("Error preparing request or " + "parsing Server response - " + e);
    }
    return result;

}