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:uk.ac.gate.cloud.client.RestClient.java

/**
 * Read a response or error message from the given connection,
 * handling any 303 redirect responses if <code>followRedirects</code>
 * is true./*from  w  w w  .ja  va 2s  . c  o  m*/
 */
private <T> T readResponseOrError(HttpURLConnection connection, TypeReference<T> responseType,
        boolean followRedirects) throws RestClientException {
    InputStream stream = null;
    try {
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            storeHeaders(connection);
            return null;
        }
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        if (responseCode < 300 || responseCode >= 400 || !followRedirects) {
            try {
                return MAPPER.readValue(stream, responseType);
            } finally {
                storeHeaders(connection);
                stream.close();
            }
        } else {
            // redirect - all redirects we care about from the GATE Cloud
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return get(location, responseType);
        }
    } catch (Exception e) {
        readError(connection);
        return null; // unreachable, as readError always throws exception
    }
}

From source file:eu.fusepool.p3.transformer.client.TransformerClientImpl.java

@Override
public Entity transform(Entity entity, MimeType... acceptedFormats) {
    HttpURLConnection connection = null;
    try {/*from   w w  w. ja va  2  s.c  o  m*/
        final URL transfromerUrl = uri.toURL();
        connection = (HttpURLConnection) transfromerUrl.openConnection();
        connection.setRequestMethod("POST");
        String acceptHeaderValue = null;
        if (acceptedFormats.length > 0) {
            final StringWriter acceptString = new StringWriter();
            double q = 1;
            for (MimeType mimeType : acceptedFormats) {
                acceptString.write(mimeType.toString());
                acceptString.write("; q=");
                acceptString.write(Double.toString(q));
                q = q * 0.9;
                acceptString.write(", ");
            }
            acceptHeaderValue = acceptString.toString();
            connection.setRequestProperty("Accept", acceptHeaderValue);
        }

        connection.setRequestProperty("Content-Type", entity.getType().toString());
        if (entity.getContentLocation() != null) {
            connection.setRequestProperty("Content-Location", entity.getContentLocation().toString());
        }

        connection.setDoOutput(true);
        connection.setUseCaches(false);
        try (OutputStream out = connection.getOutputStream()) {
            entity.writeData(out);
        }
        final int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            return getResponseEntity(connection);
        }
        if ((responseCode == 202) || (responseCode == 201)) {
            final String location = connection.getHeaderField("Location");
            if (location == null) {
                throw new RuntimeException("No location header in first 202 response");
            }
            return getAsyncResponseEntity(new URL(transfromerUrl, location), acceptHeaderValue);
        }
        throw new UnexpectedResponseException(responseCode, getResponseEntity(connection));

    } catch (IOException e) {
        throw new RuntimeException("Cannot establish connection to " + uri.toString() + " !", e);
    } catch (MimeTypeParseException ex) {
        throw new RuntimeException("Error parsing MediaType returned from Server. ", ex);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.sogrey.frame.utils.FileUtil.java

/**
 * ????.//  w  ww .j a v a 2  s .com
 *
 * @param url
 *         ?
 *
 * @return ??
 */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (StrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e(FileUtil.class, "???");
    }
    return name;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

private void testVerifyHttpGetHeaders(X509Certificate caCertificate, BigInteger serialNumber) throws Exception {
    // An OCSP request, ocspTestCert is already created in earlier tests
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber));
    OCSPReq req = gen.build();/*from   ww  w.j  av a 2 s.  c o  m*/
    String reqString = new String(Base64.encode(req.getEncoded(), false));
    URL url = new URL(httpReqPath + '/' + resourceOcsp + '/' + URLEncoder.encode(reqString, "UTF-8"));
    log.debug("OCSP Request: " + url.toExternalForm());
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    assertEquals(
            "Response code did not match. (Make sure you allow encoded slashes in your appserver.. add -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in Tomcat)",
            200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", OCSPRespBuilder.SUCCESSFUL, response.getStatus());
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    // Just output the headers to stdout so we can visually inspect them if
    // something goes wrong
    Set<String> keys = con.getHeaderFields().keySet();
    for (String field : keys) {
        List<String> values = con.getHeaderFields().get(field);
        for (String value : values) {
            log.info(field + ": " + value);
        }
    }
    String eTag = con.getHeaderField("ETag");
    assertNotNull(
            "RFC 5019 6.2: No 'ETag' HTTP header present as it SHOULD. (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            eTag);
    assertTrue("ETag is messed up.",
            ("\"" + new String(
                    Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(response.getEncoded()))) + "\"")
                            .equals(eTag));
    long date = con.getHeaderFieldDate("Date", -1);
    assertTrue("RFC 5019 6.2: No 'Date' HTTP header present as it SHOULD.", date != -1);
    long lastModified = con.getHeaderFieldDate("Last-Modified", -1);
    assertTrue("RFC 5019 6.2: No 'Last-Modified' HTTP header present as it SHOULD.", lastModified != -1);
    // assertTrue("Last-Modified is after response was sent",
    // lastModified<=date); This will not hold on JBoss AS due to the
    // caching of the Date-header
    long expires = con.getExpiration();
    assertTrue("Expires is before response was sent", expires >= date);
    assertTrue("RFC 5019 6.2: No 'Expires' HTTP header present as it SHOULD.", expires != 0);
    String cacheControl = con.getHeaderField("Cache-Control");
    assertNotNull("RFC 5019 6.2: No 'Cache-Control' HTTP header present as it SHOULD.", cacheControl);
    assertTrue("RFC 5019 6.2: No 'public' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("public"));
    assertTrue("RFC 5019 6.2: No 'no-transform' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("no-transform"));
    assertTrue("RFC 5019 6.2: No 'must-revalidate' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("must-revalidate"));
    Matcher matcher = Pattern.compile(".*max-age\\s*=\\s*(\\d+).*").matcher(cacheControl);
    assertTrue("RFC 5019 6.2: No 'max-age' HTTP header Cache-Control present as it SHOULD.", matcher.matches());
    int maxAge = Integer.parseInt(matcher.group(1));
    log.debug("maxAge=" + maxAge + " (expires-lastModified)/1000=" + ((expires - lastModified) / 1000));
    assertTrue(
            "thisUpdate and nextUpdate should not be the same (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            expires != lastModified);
    assertTrue("RFC 5019 6.2: [maxAge] SHOULD be 'later than thisUpdate but earlier than nextUpdate'.",
            maxAge < (expires - lastModified) / 1000);
    // assertTrue("Response cannot be produced after it was sent.",
    // brep.getProducedAt().getTime() <= date); This might not hold on JBoss
    // AS due to the caching of the Date-header
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    assertNull("No nonce should be present.", brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce));
    SingleResp[] singleResps = brep.getResponses();
    assertNotNull("SingleResps should not be null.", singleResps);
    assertTrue("Expected a single SingleResp in the repsonse.", singleResps.length == 1);
    assertEquals("Serno in response does not match serno in request.",
            singleResps[0].getCertID().getSerialNumber(), serialNumber);
    assertEquals("Status is not null (null is 'good')", singleResps[0].getCertStatus(), null);
    assertTrue(
            "RFC 5019 6.2: Last-Modified SHOULD 'be the same as the thisUpdate timestamp in the request itself'",
            singleResps[0].getThisUpdate().getTime() == lastModified);
    assertTrue("RFC 5019 6.2: Expires SHOULD 'be the same as the nextUpdate timestamp in the request itself'",
            singleResps[0].getNextUpdate().getTime() == expires);
    assertTrue("Response cannot be produced before it was last modified..",
            brep.getProducedAt().getTime() >= singleResps[0].getThisUpdate().getTime());
}

From source file:org.xcmis.restatom.collections.CmisObjectCollection.java

/**
 * Get content stream from entry.//from w  w w  .j a  va 2s .c om
 *
 * @param entry source entry
 * @param request request context
 * @return content stream as <code>ContentStream</code> or null if there is
 *         no 'content' in entry
 * @throws IOException if any i/o error occurs
 * @throws ResponseContextException other errors
 */
protected ContentStream getContentStream(Entry entry, RequestContext request)
        throws IOException, ResponseContextException {
    ContentStream contentStream = null;
    ContentTypeElement cmisContent = entry.getExtension(AtomCMIS.CONTENT);
    if (cmisContent != null) {
        CmisContentType content = cmisContent.getContent();

        InputStream is = content.getBase64();
        contentStream = new BaseContentStream(is, is.available(), null,
                org.xcmis.spi.utils.MimeType.fromString(content.getMediatype()));
    } else {
        Content content = entry.getContentElement();
        if (content != null) {
            final IRI src = content.getSrc();
            if (src != null) {
                if (src.equals(new IRI(getContentLink(getId(request), request)))) {
                    // If 'src' attribute provides URI is the same to current
                    // object (document). This may happen when client does 'check-in'
                    // or 'check-out' operation.
                } else {
                    URL url = null;
                    try {
                        url = src.toURL();
                    } catch (URISyntaxException e) {
                        String msg = "Invalid src attribute: " + src;
                        throw new ResponseContextException(createErrorResponse(msg, 400));
                    }
                    // HTTP only
                    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
                    httpConnection.setRequestMethod("GET");
                    httpConnection.setDoOutput(false);
                    httpConnection.setDoInput(true);
                    int status = httpConnection.getResponseCode();
                    if (200 == status) {
                        contentStream = new BaseContentStream(new HttpConnectionStream(httpConnection), null,
                                org.xcmis.spi.utils.MimeType
                                        .fromString(httpConnection.getHeaderField("Content-Type")));
                    } else {
                        httpConnection.disconnect();
                        String msg = "Unable get content from URI : " + src.toString() + ". Response status is "
                                + status;
                        throw new ResponseContextException(createErrorResponse(msg, 500));
                    }
                }
            } else {
                Type contentType = content.getContentType();
                org.xcmis.spi.utils.MimeType mediaType;
                if (contentType == Type.XML || contentType == Type.XHTML || contentType == Type.HTML
                        || contentType == Type.TEXT) {
                    switch (contentType) {
                    case XHTML:
                        mediaType = new org.xcmis.spi.utils.MimeType("application", "xhtml+xml");
                        break;
                    case HTML:
                        mediaType = new org.xcmis.spi.utils.MimeType("text", "html");
                        break;
                    case TEXT:
                        mediaType = new org.xcmis.spi.utils.MimeType("text", "plain");
                        break;
                    case XML:
                        mediaType = convertMimeType(content.getMimeType());
                        break;
                    default:
                        // Must never happen.
                        mediaType = new org.xcmis.spi.utils.MimeType();
                    }

                    byte[] data;
                    // XXX CMISSpaces sends XML content as Base64 encoded but
                    // Abdera waits for plain text.
                    // Done just for research work. Find good solution to fix this.
                    if (SPACES_AIR_SPECIFIC_REFERER.equalsIgnoreCase(request.getHeader("referer"))) {
                        data = Base64.decodeBase64(content.getText().getBytes());
                    } else {
                        String charset = mediaType.getParameter(CmisConstants.CHARSET);
                        if (charset == null) {
                            // workaround
                            mediaType.getParameters().put(CmisConstants.CHARSET, "UTF-8");
                        }
                        data = content.getValue().getBytes(charset == null ? "UTF-8" : charset);

                    }

                    contentStream = new BaseContentStream(data, null, mediaType);
                } else {
                    contentStream = new BaseContentStream(content.getDataHandler().getInputStream(), null,
                            convertMimeType(content.getMimeType()));
                }
            }
        }
    }
    return contentStream;
}

From source file:org.sakaiproject.content.chh.dspace.ContentHostingHandlerImplDSpace.java

public void commit(ContentCollectionEdit edit) {
    ContentCollectionDSpace ccds = null;
    if (edit instanceof ContentCollectionDSpace)
        ccds = (ContentCollectionDSpace) edit;
    else {//w  w  w .  jav a2s.c o m
        ContentEntity tmp = edit.getVirtualContentEntity();
        if (tmp instanceof ContentCollectionDSpace)
            ccds = (ContentCollectionDSpace) tmp;
        else if (tmp instanceof ContentResourceDSpace)
            ccds = ((ContentResourceDSpace) tmp).convertToCollection();
    }
    if (ccds == null)
        return; // can't do anything if the resource isn't a
    // dspace resource!

    ContentEntityDSpace encloser = resolveDSpace(ccds.realParent, ccds.endpoint, ccds.basehandle,
            ccds.parentRelativePath, ccds.chh, ccds.searchable);
    if (encloser == null || encloser.dii == null || encloser.dii.handle == null) {
        log.warn(
                "Content Hosting Handler DSpace was unable to save the contents of a collection because the enclosing collection was not found.");
        return; // parent collection has been erased
    }
    // encloser.dii.handle is the parent collection handle to which we
    // http/dav PUT this resource

    try {
        if (encloser.dii.endpoint != null && encloser.dii.handle != null) {
            String puturl = ccds.dii.endpoint;
            puturl = puturl.substring(0, puturl.lastIndexOf("/"));
            puturl = puturl + "/dso_" + encloser.dii.handle.replace("/", "%24") + "?mkcol=true";
            URL url = new URL(puturl);

            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("PUT");
            huc.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
            huc.setRequestProperty("User-Agent", "Axis/1.3");
            huc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            huc.setRequestProperty("Authorization", "Basic am9obmYlNDBjYXJldC5jYW0uYWMudWs6cGFzc3dvcmQ=");
            huc.setDoOutput(true);
            huc.connect();
            huc.getOutputStream().write(("<mkcol>" + ccds.dii.displayname + "</mkcol>").getBytes());
            huc.getOutputStream().flush();
            int httpResponseCode = huc.getResponseCode();
            String handleInsideJunk = huc.getHeaderField("Location");
            if (handleInsideJunk == null)
                return;
            ccds.dii.handle = handleInsideJunk
                    .substring(5/* skip the /dso_ prefix */ + handleInsideJunk.lastIndexOf("/"))
                    .replace("%24", "/");
        }
    } catch (IOException e) {
        log.warn(
                "Content Hosting Handler DSpace was unable to save the contents of a collection because DSpace refused the operation.",
                e);
        return; // file system error -- operation cannot be performed
    } catch (SecurityException e) {
        log.warn(
                "Content Hosting Handler DSpace was unable to save the contents of a collection because the JVM SecurityManager refused the operation.",
                e);
        return; // permissions error -- operation cannot be performed
    }
    checkForUnmountRequest(edit);
}

From source file:de.alosdev.android.customerschoice.CustomersChoice.java

private void internalConfigureByNetwork(final Context context, String fileAddress) {
    new AsyncTask<String, Void, Void>() {
        @Override/*from w  w  w.  ja  va 2  s  . com*/
        protected Void doInBackground(String... args) {
            String value = args[0];
            try {
                final SharedPreferences preferences = getPreferences(context);
                final URL url = new URL(value);
                log.d(TAG, "read from: ", value);

                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);

                // set etag header if existing
                final String fieldEtag = preferences.getString(getPreferencesKey(value, FIELD_ETAG), null);
                if (null != fieldEtag) {
                    conn.setRequestProperty("If-None-Match", fieldEtag);
                }

                // set modified since header if existing
                final long fieldLastModified = preferences
                        .getLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), 0);
                if (fieldLastModified > 0) {
                    conn.setIfModifiedSince(fieldLastModified);
                }
                conn.connect();

                final int response = conn.getResponseCode();

                if (HttpStatus.SC_OK == response) {
                    log.d(TAG, "found file");
                    readFromInputStream(conn.getInputStream());

                    // writing caching information into preferences
                    final Editor editor = preferences.edit();
                    editor.putString(getPreferencesKey(value, FIELD_ETAG), conn.getHeaderField("ETag"));
                    editor.putLong(getPreferencesKey(value, FIELD_LAST_MODIFIED),
                            conn.getHeaderFieldDate("Last-Modified", 0));
                    editor.commit();
                } else if (HttpStatus.SC_NOT_MODIFIED == response) {
                    log.i(TAG, "no updates, file not modified: ", value);
                } else {
                    log.e(TAG, "cannot read from: ", value, " and get following response code:", response);
                }
            } catch (MalformedURLException e) {
                log.e(TAG, e, "the given URL is malformed: ", value);
            } catch (IOException e) {
                log.e(TAG, e, "Error during reading the file: ", value);
            }
            return null;
        }

    }.execute(fileAddress);
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public String responseCaptcha(String responseCaptcha) {
    String url = "https://ipv4.google.com/sorry/CaptchaRedirect";
    String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha="
            + responseCaptcha + "&submit=Enviar";
    String newCookie = "";

    try {//from  w w w . j  a  v a2s. c  om
        URL obj = new URL(request);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("Host", "ipv4.google.com");
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com");
        con.addRequestProperty("Connection", "keep-alive");
        con.setRequestProperty("Referer", referer);
        //con.connect();
        boolean redirect = false;
        con.setInstanceFollowRedirects(false);
        int status = con.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 = con.getHeaderField("Location");

            // open the new connnection again
            con = (HttpURLConnection) new URL(newUrl).openConnection();
            con.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
            con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            con.setRequestProperty("Referer", referer);
            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setRequestProperty("Cookie", tokenCookie);
            con.addRequestProperty("Connection", "keep-alive");

            // Find the cookie
            String nextURL = URLDecoder.decode(newUrl, "UTF-8");
            String[] k = nextURL.split("&");
            for (String a : k) {
                if (a.startsWith("google_abuse=")) {
                    String temp = a.replace("google_abuse=", "");
                    String[] c = temp.split(";");
                    for (String j : c) {
                        if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) {
                            newCookie = j;
                        }
                    }

                }
            }
        }

        con.connect();

        if (con.getResponseCode() == 200) {
            newCookie = tokenCookie;
        }
    } catch (IOException e) {
        e.printStackTrace();

    }

    return newCookie;

}

From source file:com.BeatYourRecord.SubmitActivity.java

private ResumeInfo resumeFileUpload(String uploadUrl)
        throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException {
    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestProperty("Content-Range", "bytes */*");
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
    urlConnection.setFixedLengthStreamingMode(0);

    HttpURLConnection.setFollowRedirects(false);

    urlConnection.connect();/*  www .  j a  v a2  s .c  om*/
    int responseCode = urlConnection.getResponseCode();

    if (responseCode >= 300 && responseCode < 400) {
        int nextByteToUpload;
        String range = urlConnection.getHeaderField("Range");
        if (range == null) {
            Log.d(LOG_TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl));
            nextByteToUpload = 0;
        } else {
            Log.d(LOG_TAG, String.format("Range header is '%s'.", range));
            String[] parts = range.split("-");
            if (parts.length > 1) {
                nextByteToUpload = Integer.parseInt(parts[1]) + 1;
            } else {
                nextByteToUpload = 0;
            }
        }
        return new ResumeInfo(nextByteToUpload);
    } else if (responseCode >= 200 && responseCode < 300) {
        return new ResumeInfo(parseVideoId(urlConnection.getInputStream()));
    } else if (responseCode == 500) {
        // TODO this is a workaround for current problems with resuming uploads while switching transport (Wifi->EDGE)
        throw new Internal500ResumeException(
                String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl,
                        urlConnection.getResponseMessage(), responseCode));
    } else {
        throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl,
                urlConnection.getResponseMessage(), responseCode));
    }
}

From source file:org.kohsuke.github.GitHub.java

/**
 * Ensures if a GitHub Enterprise server is configured in private mode.
 *
 * @return {@code true} if private mode is enabled. If it tries to use this method with GitHub, returns {@code
 * false}.//  w  w w  .  ja v a2 s  . c o  m
 */
private boolean isPrivateModeEnabled() {
    try {
        HttpURLConnection uc = getConnector().connect(getApiURL("/"));
        /*
        $ curl -i https://github.mycompany.com/api/v3/
        HTTP/1.1 401 Unauthorized
        Server: GitHub.com
        Date: Sat, 05 Mar 2016 19:45:01 GMT
        Content-Type: application/json; charset=utf-8
        Content-Length: 130
        Status: 401 Unauthorized
        X-GitHub-Media-Type: github.v3
        X-XSS-Protection: 1; mode=block
        X-Frame-Options: deny
        Content-Security-Policy: default-src 'none'
        Access-Control-Allow-Credentials: true
        Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
        Access-Control-Allow-Origin: *
        X-GitHub-Request-Id: dbc70361-b11d-4131-9a7f-674b8edd0411
        Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
        X-Content-Type-Options: nosniff
         */
        try {
            return uc.getResponseCode() == HTTP_UNAUTHORIZED
                    && uc.getHeaderField("X-GitHub-Media-Type") != null;
        } finally {
            // ensure that the connection opened by getResponseCode gets closed
            try {
                IOUtils.closeQuietly(uc.getInputStream());
            } catch (IOException ignore) {
                // ignore
            }
            IOUtils.closeQuietly(uc.getErrorStream());
        }
    } catch (IOException e) {
        return false;
    }
}