Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java

protected File downloadDatabase(final String url, final File existingDb) throws IOException {
    LOGGER.info("[" + getClass().getSimpleName() + "] Downloading database: " + url);
    final URL dbURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) dbURL.openConnection();

    if (useModifiedTimestamp(existingDb)) {
        conn.setIfModifiedSince(existingDb.lastModified());
        if (eTag != null) {
            conn.setRequestProperty("If-None-Match", eTag);
        }/*from  www . j  a  v a2s.c  om*/
    }

    InputStream in = conn.getInputStream();
    eTag = conn.getHeaderField("ETag");

    if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        LOGGER.info("[" + getClass().getSimpleName() + "] " + url
                + " not modified since our existing database's last update time of "
                + new Date(existingDb.lastModified()));
        return existingDb;
    }

    if (sourceCompressed) {
        in = new GZIPInputStream(in);
    }

    final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
    final OutputStream out = new FileOutputStream(outputFile);

    IOUtils.copy(in, out);
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);

    return outputFile;
}

From source file:android.widget.TiVideoView4.java

private void setDataSource() {
    try {/*  w  ww. jav a  2  s.c om*/
        if (mUri.getScheme().equals("http") || mUri.getScheme().equals("https")) {
            // Media player doesn't handle redirects, try to follow them here
            while (true) {
                // java.net.URL doesn't handle rtsp
                if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp"))
                    break;

                URL url = new URL(mUri.toString());
                HttpURLConnection cn = (HttpURLConnection) url.openConnection();
                cn.setInstanceFollowRedirects(false);
                String location = cn.getHeaderField("Location");
                if (location != null) {
                    String host = mUri.getHost();
                    int port = mUri.getPort();
                    String scheme = mUri.getScheme();
                    mUri = Uri.parse(location);
                    if (mUri.getScheme() == null) {
                        // Absolute URL on existing host/port/scheme
                        if (scheme == null) {
                            scheme = "http";
                        }
                        String authority = port == -1 ? host : host + ":" + port;
                        mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build();
                    }
                } else {
                    break;
                }
            }
        }
        mMediaPlayer.setDataSource(getContext(), mUri);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java

public TequilaToken getTequilaTokenForMoodle() throws TException {
    System.out.println("getTequilaTokenForMoodle");
    try {//from  w  w w  .  j a va2  s. c o m
        HttpURLConnection conn2 = (HttpURLConnection) new URL("http://moodle.epfl.ch/auth/tequila/index.php")
                .openConnection();
        conn2.setInstanceFollowRedirects(false);
        conn2.getInputStream();
        URL url = new URL(conn2.getHeaderField("Location"));
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(url.getQuery(), params, "UTF-8");
        TequilaToken teqToken = new TequilaToken(params.getString("requestkey"));
        Cookie cookie = new Cookie();
        for (String header : conn2.getHeaderFields().get("Set-Cookie")) {
            cookie.addFromHeader(header);
        }
        teqToken.setLoginCookie(cookie.cookie());
        return teqToken;
    } catch (IOException e) {
        e.printStackTrace();
        throw new TException("Failed to getTequilaToken from upstream server");
    }
}

From source file:biz.gabrys.lesscss.extended.compiler.source.HttpSource.java

private HttpURLConnection makeConnection(final boolean fetchResponseBody) {
    HttpURLConnection connection;
    int responseCode;
    URL resourceUrl = url;//from w w  w. j a  v  a2s .  c  om
    boolean redirected = false;
    while (true) {
        try {
            connection = (HttpURLConnection) resourceUrl.openConnection();
            connection.setRequestMethod(fetchResponseBody ? "GET" : "HEAD");
            responseCode = connection.getResponseCode();
        } catch (final IOException e) {
            throw new SourceException(e);
        }

        if (!REDIRECT_CODES.contains(responseCode)) {
            break;
        }
        redirected = true;
        final String location = connection.getHeaderField("Location");
        try {
            resourceUrl = new URL(location);
        } catch (final MalformedURLException e) {
            throw new SourceException(String.format("Invalid Location header: %s", location), e);
        }
    }
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new SourceException(createDownloadErrorMessage(resourceUrl, redirected, responseCode));
    }
    return connection;
}

From source file:org.okj.im.core.service.QQHttpService.java

/**
 * ??httpclient?//from  w  w w .  j  av  a2 s  .c o  m
 * @param url
 * @param method
 * @param exParam
 * @return
 */
public String sendHttpMessage(String url, String method, ExParam exParam) {
    if (exParam == null) {
        exParam = new ExParam();
    }
    HttpURLConnection conn = null;
    do {
        conn = connect(url, method, exParam); //
    } while (!checkResponseCode(conn));

    //?cookies
    if (conn.getHeaderFields().get("Set-Cookie") != null) {
        StringBuffer cookies = new StringBuffer();
        for (String s : conn.getHeaderFields().get("Set-Cookie")) {
            cookies.append(s);
        }
        exParam.setCookie(cookies.toString());
    }

    if (StringUtils.equalsIgnoreCase("gzip", conn.getHeaderField("Content-Encoding"))) {
        return getGzipResponseString(conn);
    }
    return getResponseString(conn);
}

From source file:URLTree.FindOptimalPath.java

public void varifiedSequece(List<FilterURL> varifiedList, PrintWriter writer) {
    for (int i = 0; i < varifiedList.size() - 1; i++) {
        if (varifiedList.get(i).getReversedURL().contains(varifiedList.get(i + 1).getReversedURL())) {

        } else {//  w ww .  j  a  v a 2 s.  c  o m
            String nodesName[] = varifiedList.get(i).getReversedURL().split("-");
            if (nodesName.length == 2) {
                try {
                    String url2Domain = "http://" + nodesName[1] + "." + nodesName[0];
                    URL url = new URL(url2Domain);
                    // open connection
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url
                            .openConnection(Proxy.NO_PROXY);

                    // stop following browser redirect
                    httpURLConnection.setInstanceFollowRedirects(false);
                    httpURLConnection.setConnectTimeout(15000);
                    httpURLConnection.setReadTimeout(15000);
                    // extract location header containing the actual destination URL
                    String expandedURL = httpURLConnection.getHeaderField("Location");
                    httpURLConnection.disconnect();
                    if (expandedURL != null) {
                        System.out.println("Correct: " + expandedURL);
                        writer.println(
                                varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount());
                    }

                } catch (Exception e) {
                    System.out.println("Incorrect: " + e);
                }
            } else {
                writer.println(varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount());
            }

        }

    }
}

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  w  w  w  . ja v a  2  s .c  o  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.wymiwyg.wrhapi.test.BaseTests.java

@Test
public void testEmptyBodyAnHeader() throws Exception {
    final String body = "";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, final Response response) throws HandlerException {
            log.info("handling testEmptyBody");
            response.setResponseStatus(ResponseStatus.CREATED);
            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    try {
                        response.setHeader(HeaderName.CONTENT_TYPE, "text/plain");
                    } catch (HandlerException ex) {
                        throw new RuntimeException(ex);
                    }//from   w ww . j a  va2  s.  co m
                    out.write(ByteBuffer.wrap(body.getBytes()));
                    out.close();
                }
            });
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection();
        assertEquals("text/plain", connection.getHeaderField("Content-Type"));
        assertEquals(ResponseStatus.CREATED.getCode(), connection.getResponseCode());
        Reader reader = new InputStreamReader(connection.getInputStream());
        StringWriter stringWriter = new StringWriter();

        for (int ch = reader.read(); ch != -1; ch = reader.read()) {
            stringWriter.write(ch);
        }

        assertEquals(body, stringWriter.toString());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:com.hellofyc.base.net.http.HttpUtils.java

public HttpResponse request() {
    if (mDebug) {
        FLog.i("REQUEST URL:" + mUrlString);
        FLog.i("REQUEST PARAMS:" + mRequestParams.getArrayMap().toString());
        FLog.i("REQUEST STRING:" + mRequestParams.getString());
    }//from   w  ww .  j a  v  a2 s  .  c o m

    if (mStackTrace) {
        getInvokeStackTraceElement();
    }

    HttpResponse response = new HttpResponse();
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(mUrlString).openConnection();
        configConnection(connection);
        response.code = connection.getResponseCode();
        if (mDebug)
            FLog.i("===responseCode:" + response.code);
        if (response.code == HttpURLConnection.HTTP_OK) {
            String responseText = IoUtils.readStream(connection.getInputStream());
            String cookie = connection.getHeaderField("Set-Cookie");
            if (mDebug)
                FLog.i("===responseText:" + responseText);
            if (mDebug)
                FLog.i("===cookie:" + cookie);
            response.cookies = HttpCookie.parse(cookie);
            response.text = responseText;
        } else {
            response.text = connection.getResponseMessage();
        }
    } catch (UnknownHostException e) {
        if (mDebug)
            FLog.e(e);
        response.code = HttpResponse.STATUS_CODE_NET;
        response.text = "";
        return response;
    } catch (IOException e) {
        if (mDebug)
            FLog.e(e);
        response.code = HttpResponse.STATUS_CODE_UNKNOWN;
        response.text = "UNKNOWN";
        return response;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return response;
}

From source file:com.atlassian.launchpad.jira.whiteboard.WhiteboardTabPanel.java

@Override
public List<IssueAction> getActions(Issue issue, User remoteUser) {
    List<IssueAction> messages = new ArrayList<IssueAction>();

    //retrieve and validate url from custom field
    CustomField bpLinkField = ComponentAccessor.getCustomFieldManager()
            .getCustomFieldObjectByName(LAUNCHPAD_URL_FIELD_NAME);

    if (bpLinkField == null) {
        messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME
                + "\" custom field not available. Cannot process Gerrit Review comments"));
        return messages;
    }//  www .  ja v a2 s  .com

    Object bpURLFieldObj = issue.getCustomFieldValue(bpLinkField);
    if (bpURLFieldObj == null) {
        messages.add(new GenericMessageAction("\"" + LAUNCHPAD_URL_FIELD_NAME
                + "\" not provided. Please provide the Launchpad URL to view the whiteboard for this issue."));
        return messages;
    }

    String bpURL = bpURLFieldObj.toString().trim();

    if (bpURL.length() == 0) {
        messages.add(
                new GenericMessageAction("To view the Launchpad Blueprint for this issue please provide the "
                        + LAUNCHPAD_URL_FIELD_NAME));
        return messages;
    }

    if (!bpURL.matches(URL_REGEX)) {
        messages.add(new GenericMessageAction(
                "Launchpad URL not properly formatted. Please provide URL that appears as follows:<br/> https://blueprints.launchpad.net/devel/PROJECT NAME/+spec/BLUEPRINT NAME"));
        return messages;
    }

    String apiQuery = bpURL.substring(
            (bpURL.lastIndexOf(BASE_LAUNCHPAD_BLUEPRINT_HOST) + BASE_LAUNCHPAD_BLUEPRINT_HOST.length()));

    String url = BASE_LAUNCHPAD_API_URL + API_VERSION + apiQuery;

    try {
        //establish api connection
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            // get redirect url from "location" header field
            String newUrl = conn.getHeaderField("Location");

            // open the new connection
            conn = (HttpURLConnection) new URL(newUrl).openConnection();
        }

        //parse returned json
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer json = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();

        //generate tab content
        JSONTokener tokener = new JSONTokener(json.toString());
        JSONObject finalResult = new JSONObject(tokener);
        if (finalResult.has(WHITEBOARD) && finalResult.getString(WHITEBOARD).length() > 0) {
            messages.add(new GenericMessageAction(
                    escapeHtml(finalResult.getString(WHITEBOARD)).replaceAll("\n", "<br/>")));
        } else {
            messages.add(new GenericMessageAction("No whiteboard for this blueprint."));
        }

    } catch (JSONException e) {
        // whiteboard JSON key not found
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        //unable to find the requested whiteboard
        messages.add(new GenericMessageAction(
                "Unable to find desired blueprint. Please check that the URL references the correct blueprint."));
        return messages;
    } catch (IOException e) {
        // Exception in attempting to read from Launchpad API
        e.printStackTrace();
    }

    return messages;
}