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:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java

private String sendRequest(Map<String, String> parameters) {
    URL url = createRequestUrl(parameters);
    HttpURLConnection urlConn;

    try {/*from   w ww  .  jav a  2s  .com*/
        urlConn = (HttpURLConnection) url.openConnection();
        // setup url connection
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setInstanceFollowRedirects(false);
        // add content type
        urlConn.setRequestProperty("Content-Type", CONTENT_TYPE);
        // add cookie information
        if (cookie != null)
            urlConn.setRequestProperty("Cookie", cookie);

        // send request
        urlConn.connect();

        // detect redirect
        int code = urlConn.getResponseCode();
        boolean moved = code == HttpURLConnection.HTTP_MOVED_PERM | code == HttpURLConnection.HTTP_MOVED_TEMP;
        if (moved) {
            String location = urlConn.getHeaderField("Location");
            List<String> headerVals = urlConn.getHeaderFields().get("Set-Cookie");
            for (String val : headerVals) {
                if (val.startsWith(COOKIE))
                    cookie = val;
            }
            url = createRedirectUrl(location);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestProperty("Cookie", cookie);
        }

        // read response
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = input.readLine()) != null)
            response.append(line).append("\n");
        input.close();

        if (isLogDebugEnabled())
            logDebug("Response: " + response);

        return response.toString();
    } catch (IOException e) {
        logError("Sending request to Wimba Classroom failed. Request: " + url.toString(), e);
        return "";
    }
}

From source file:com.trafficspaces.api.controller.Connector.java

public String sendRequest(String path, String contentType, String method, String data)
        throws IOException, TrafficspacesAPIException {

    URL url = new URL(endPoint.baseURI + path);

    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);/* w  w  w  .  java  2s . co m*/
    httpCon.setRequestMethod(method.toUpperCase());

    String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes());
    httpCon.setRequestProperty("Authorization", basicAuth);

    httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8");
    httpCon.setRequestProperty("Accept", contentType);

    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        httpCon.setRequestProperty("Content-Length", String.valueOf(data.length()));
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);
        out.close();
    } else {
        httpCon.connect();
    }

    char[] responseData = null;
    try {
        responseData = readResponseData(httpCon.getInputStream(), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        // HTTP 404. Ignore and return null
    }
    String responseDataString = null;
    if (responseData != null) {
        int responseCode = httpCon.getResponseCode();
        String redirectURL = null;
        if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_CREATED)
                && (redirectURL = httpCon.getHeaderField("Location")) != null) {
            //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL);
            return sendRequest(redirectURL, contentType);
        }
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            throw new TrafficspacesAPIException(
                    "HTTP Error: " + responseCode + "; Data: " + new String(responseData));
        }
        //System.out.println("Headers: " + httpCon.getHeaderFields());
        //System.out.println("Data: " + new String(responseData));
        responseDataString = new String(responseData);
    }
    return responseDataString;
}

From source file:org.jets3t.service.TestRestS3Service.java

public void testUrlSigningUsingSignatureVersion2() throws Exception {
    RestS3Service service = (RestS3Service) getStorageService(getCredentials());
    StorageBucket bucket = createBucketForTest("testUrlSigningUsingSignatureVersion2");
    String bucketName = bucket.getName();

    try {/*  w ww .j  a va 2 s  .  c  o  m*/
        // Create test object, with private ACL
        String dataString = "Text for the URL Signing test object...";
        S3Object object = new S3Object("Testing URL Signing", dataString);
        object.setContentType("text/html");
        object.addMetadata(service.getRestMetadataPrefix() + "example-header", "example-value");
        object.setAcl(AccessControlList.REST_CANNED_PRIVATE);

        // Determine what the time will be in 5 minutes.
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, 5);
        Date expiryDate = cal.getTime();

        // Create a signed HTTP PUT URL.
        String signedPutUrl = service.createSignedPutUrl(bucket.getName(), object.getKey(),
                object.getMetadataMap(), expiryDate, false);

        // Put the object in S3 using the signed URL (no AWS credentials required)
        RestS3Service anonymousS3Service = new RestS3Service(null);
        anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);

        // Ensure the object was created.
        StorageObject objects[] = service.listObjects(bucketName, object.getKey(), null);
        assertEquals("Signed PUT URL failed to put/create object", objects.length, 1);

        // Change the object's content-type and ensure the signed PUT URL disallows the put.
        object.setContentType("application/octet-stream");
        try {
            anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);
            fail("Should not be able to use a signed URL for an object with a changed content-type");
        } catch (ServiceException e) {
            object.setContentType("text/html");
        }

        // Add an object header and ensure the signed PUT URL disallows the put.
        object.addMetadata(service.getRestMetadataPrefix() + "example-header-2", "example-value");
        try {
            anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);
            fail("Should not be able to use a signed URL for an object with changed metadata");
        } catch (ServiceException e) {
            object.removeMetadata(service.getRestMetadataPrefix() + "example-header-2");
        }

        // Change the object's name and ensure the signed PUT URL uses the signed name, not the object name.
        String originalName = object.getKey();
        object.setKey("Testing URL Signing 2");
        object.setDataInputStream(new ByteArrayInputStream(dataString.getBytes()));
        object = anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);
        assertEquals("Ensure returned object key is renamed based on signed PUT URL", originalName,
                object.getKey());

        // Test last-resort MD5 sanity-check for uploaded object when ETag is missing.
        S3Object objectWithoutETag = new S3Object("Object Without ETag");
        objectWithoutETag.setContentType("text/html");
        String objectWithoutETagSignedPutURL = service.createSignedPutUrl(bucket.getName(),
                objectWithoutETag.getKey(), objectWithoutETag.getMetadataMap(), expiryDate, false);
        objectWithoutETag.setDataInputStream(new ByteArrayInputStream(dataString.getBytes()));
        objectWithoutETag.setContentLength(dataString.getBytes().length);
        anonymousS3Service.putObjectWithSignedUrl(objectWithoutETagSignedPutURL, objectWithoutETag);
        service.deleteObject(bucketName, objectWithoutETag.getKey());

        // Ensure we can't get the object with a normal URL.
        String s3Url = "https://s3.amazonaws.com";
        URL url = new URL(s3Url + "/" + bucket.getName() + "/" + RestUtils.encodeUrlString(object.getKey()));
        assertEquals("Expected denied access (403) error", 403,
                ((HttpURLConnection) url.openConnection()).getResponseCode());

        // Create a signed HTTP GET URL.
        String signedGetUrl = service.createSignedGetUrl(bucket.getName(), object.getKey(), expiryDate, false);

        // Ensure the signed URL can retrieve the object.
        url = new URL(signedGetUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        assertEquals("Expected signed GET URL (" + signedGetUrl + ") to retrieve object with response code 200",
                200, conn.getResponseCode());

        // Sanity check the data in the S3 object.
        String objectData = (new BufferedReader(new InputStreamReader(conn.getInputStream()))).readLine();
        assertEquals("Unexpected data content in S3 object", dataString, objectData);

        // Confirm we got the expected Content-Type
        assertEquals("text/html", conn.getHeaderField("content-type"));

        // Modify response data via special "response-*" request parameters
        signedGetUrl = service.createSignedUrl("GET", bucket.getName(), object.getKey(),
                "response-content-type=text/plain&response-content-encoding=latin1", null, // No headers
                (expiryDate.getTime() / 1000) // Expiry time after epoch in seconds
        );
        url = new URL(signedGetUrl);
        conn = (HttpURLConnection) url.openConnection();
        assertEquals("text/plain", conn.getHeaderField("content-type"));
        assertEquals("latin1", conn.getHeaderField("content-encoding"));

        // Clean up.
        service.deleteObject(bucketName, object.getKey());
    } finally {
        cleanupBucketForTest("testUrlSigningUsingSignatureVersion2");
    }
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

public byte[] sendCmpHttp(final byte[] message, final int httpRespCode, String cmpAlias, String host,
        final String fullURL) throws IOException {

    String urlString = fullURL;//  www  .  ja  va  2  s.c  o  m
    if (urlString == null) {
        if (host == null) {
            host = "127.0.0.1";
            log.info("Using default CMP Server IP address: localhost");
        }
        final String httpReqPath = "http://" + host + ":8080/ejbca";
        final String resourceCmp = "publicweb/cmp";
        if (cmpAlias == null) {
            cmpAlias = "cmp";
            log.info("Using default CMP alias: " + cmpAlias);
        }
        urlString = httpReqPath + '/' + resourceCmp + '/' + cmpAlias;
    }

    log.info("Using CMP URL: " + urlString);
    URL url = new URL(urlString);
    final HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-type", "application/pkixcmp");
    con.connect();
    // POST it
    OutputStream os = con.getOutputStream();
    os.write(message);
    os.close();

    final int conResponseCode = con.getResponseCode();
    if (conResponseCode != httpRespCode) {
        log.info("Unexpected HTTP response code: " + conResponseCode);
    }
    // Only try to read the response if we expected a 200 (ok) response
    if (httpRespCode != 200) {
        return null;
    }
    // Some appserver (Weblogic) responds with
    // "application/pkixcmp; charset=UTF-8"
    final String conContentType = con.getContentType();
    if (conContentType == null) {
        log.error("No content type in response.");
        System.exit(1);
    }
    if (!StringUtils.equals("application/pkixcmp", conContentType)) {
        log.info("Content type is not 'application/pkixcmp'");
    }
    // Check that the CMP respone has the cache-control headers as specified in 
    // http://tools.ietf.org/html/draft-ietf-pkix-cmp-transport-protocols-14
    final String cacheControl = con.getHeaderField("Cache-Control");
    if (cacheControl == null) {
        log.error("'Cache-Control' header is not present.");
        System.exit(1);
    }
    if (!StringUtils.equals("no-cache", cacheControl)) {
        log.error("Cache-Control is not 'no-cache'");
        System.exit(1);
    }
    final String pragma = con.getHeaderField("Pragma");
    if (pragma == null) {
        log.error("'Pragma' header is not present.");
        System.exit(1);
    }
    if (!StringUtils.equals("no-cache", pragma)) {
        log.error("Pragma is not 'no-cache'");
        System.exit(1);
    }
    // Now read in the bytes
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and CMP requests are small enough
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    if ((respBytes == null) || (respBytes.length <= 0)) {
        log.error("No response from server");
        System.exit(1);
    }
    return respBytes;
}

From source file:bluevia.InitService.java

boolean subscribeNotifications() {
    boolean result = true;
    String[] countryShortNumbers = { MO_UK, MO_SP, MO_GE, MO_BR, MO_MX, MO_AR, MO_CH, MO_CO };
    int i = 0;//from   w ww .  ja  v a2  s . c o  m

    for (i = 0; i < countryShortNumbers.length; i++) {
        try {
            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(Util.BlueViaOAuth.consumer_key,
                    Util.BlueViaOAuth.consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            URL apiURI = new URL(
                    "https://api.bluevia.com/services/REST/SMS/inbound/subscriptions?version=v1&alt=json");

            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

            Random rand = new Random();
            Date now = new Date();

            rand.setSeed(now.getTime());
            Long correlator = rand.nextLong();
            if (correlator < 0)
                correlator = -1 * correlator;

            String jsonSubscriptionMsg = "{\"smsNotification\":{\"reference\":{\"correlator\": \"%s\",\"endpoint\": \"%s\"},\"destinationAddress\":{\"phoneNumber\":\"%s\"},\"criteria\":\"%s\"}}";
            String szBody = String.format(jsonSubscriptionMsg, "bv" + correlator.toString().substring(0, 16),
                    Util.getCallbackDomain() + "/notifySmsReception", countryShortNumbers[i],
                    Util.BlueViaOAuth.app_keyword);

            request.setRequestProperty("Content-Type", "application/json");
            request.setRequestProperty("Content-Length", "" + Integer.toString(szBody.getBytes().length));
            request.setRequestMethod("POST");
            request.setDoOutput(true);

            consumer.sign(request);
            request.connect();

            OutputStream os = request.getOutputStream();
            os.write(szBody.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                Util.addUnsubscriptionURI(countryShortNumbers[i], request.getHeaderField("Location"),
                        "bv" + correlator.toString().substring(0, 16));
            else {
                logger.severe(String.format("Error %d registering Notification URLs:%s", rc,
                        request.getResponseMessage()));
            }
        } catch (Exception e) {
            logger.severe("Exception raised: %s" + e.getMessage());
        }
    }

    return result;
}

From source file:org.jets3t.service.TestRestS3Service.java

public void testUrlSigningUsingSignatureVersion4() throws Exception {
    String requestSignatureVersion = "AWS4-HMAC-SHA256";
    // NOTE: AWS region eu-central-1 only supports signature version 4
    String region = "eu-central-1";

    RestS3Service service = (RestS3Service) getStorageService(getCredentials());
    StorageBucket bucket = createBucketForTest("testUrlSigningUsingSignatureVersion4", region);
    String bucketName = bucket.getName();

    try {//from w w w .j  a v a  2s. c om
        // Create test object, with private ACL
        String dataString = "Text for the URL Signing test object...";
        S3Object object = new S3Object("Testing URL Signing", dataString);
        object.setContentType("text/html");
        object.addMetadata(service.getRestMetadataPrefix() + "example-header", "example-value");
        object.setAcl(AccessControlList.REST_CANNED_PRIVATE);

        // Determine what the time will be in 5 minutes.
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, 5);
        Date expiryDate = cal.getTime();
        long secondsSinceEpoch = expiryDate.getTime() / 1000;

        // Create a signed HTTP PUT URL.
        String signedPutUrl = service.createSignedUrlUsingSignatureVersion(requestSignatureVersion, region,
                "PUT", bucket.getName(), object.getKey(), "", // specialParamName
                object.getMetadataMap(), secondsSinceEpoch, false, // isVirtualHost,
                false, // isHttps
                false // isDnsBucketNamingDisabled
        );

        // Put the object in S3 using the signed URL (no AWS credentials required)
        RestS3Service anonymousS3Service = new RestS3Service(null);
        anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);

        // Ensure the object was created.
        StorageObject objects[] = service.listObjects(bucketName, object.getKey(), null);
        assertEquals("Signed PUT URL failed to put/create object", objects.length, 1);

        // Change the object's content-type and ensure the signed PUT URL disallows the put.
        object.setContentType("application/octet-stream");
        try {
            anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);
            fail("Should not be able to use a signed URL for an object with a changed content-type");
        } catch (ServiceException e) {
            object.setContentType("text/html");
        }

        // Add an object header and ensure the signed PUT URL disallows the put.
        object.addMetadata(service.getRestMetadataPrefix() + "example-header-2", "example-value");
        try {
            anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);
            fail("Should not be able to use a signed URL for an object with changed metadata");
        } catch (ServiceException e) {
            object.removeMetadata(service.getRestMetadataPrefix() + "example-header-2");
        }

        // Change the object's name and ensure the signed PUT URL uses the signed name, not the object name.
        String originalName = object.getKey();
        object.setKey("Testing URL Signing 2");
        object.setDataInputStream(new ByteArrayInputStream(dataString.getBytes()));
        object = anonymousS3Service.putObjectWithSignedUrl(signedPutUrl, object);
        assertEquals("Ensure returned object key is renamed based on signed PUT URL", originalName,
                object.getKey());

        // Test last-resort MD5 sanity-check for uploaded object when ETag is missing.
        S3Object objectWithoutETag = new S3Object("Object Without ETag");
        objectWithoutETag.setContentType("text/html");
        String objectWithoutETagSignedPutURL = service.createSignedUrlUsingSignatureVersion(
                requestSignatureVersion, region, "PUT", bucket.getName(), objectWithoutETag.getKey(), "", // specialParamName
                objectWithoutETag.getMetadataMap(), secondsSinceEpoch, false, // isVirtualHost,
                false, // isHttps
                false // isDnsBucketNamingDisabled
        );
        objectWithoutETag.setDataInputStream(new ByteArrayInputStream(dataString.getBytes()));
        objectWithoutETag.setContentLength(dataString.getBytes().length);
        anonymousS3Service.putObjectWithSignedUrl(objectWithoutETagSignedPutURL, objectWithoutETag);
        service.deleteObject(bucketName, objectWithoutETag.getKey());

        // Ensure we can't get the object with a normal URL.
        String s3Url = "https://s3-eu-central-1.amazonaws.com";
        URL url = new URL(s3Url + "/" + bucket.getName() + "/" + RestUtils.encodeUrlString(object.getKey()));
        assertEquals("Expected denied access (403) error", 403,
                ((HttpURLConnection) url.openConnection()).getResponseCode());

        // Create a signed HTTP GET URL.
        String signedGetUrl = service.createSignedUrlUsingSignatureVersion(requestSignatureVersion, region,
                "GET", bucket.getName(), object.getKey(), "", // specialParamName
                null, // headers map
                secondsSinceEpoch, false, // isVirtualHost,
                false, // isHttps
                false // isDnsBucketNamingDisabled
        );

        // Ensure the signed URL can retrieve the object.
        url = new URL(signedGetUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        assertEquals("Expected signed GET URL (" + signedGetUrl + ") to retrieve object with response code 200",
                200, conn.getResponseCode());

        // Sanity check the data in the S3 object.
        String objectData = (new BufferedReader(new InputStreamReader(conn.getInputStream()))).readLine();
        assertEquals("Unexpected data content in S3 object", dataString, objectData);

        // Confirm we got the expected Content-Type
        assertEquals("text/html", conn.getHeaderField("content-type"));

        // Modify response data via special "response-*" request parameters
        signedGetUrl = service.createSignedUrlUsingSignatureVersion(requestSignatureVersion, region, "GET",
                bucket.getName(), object.getKey(),
                "response-content-type=text/plain&response-content-encoding=latin1", // specialParamName
                null, // headers map
                secondsSinceEpoch, false, // isVirtualHost,
                false, // isHttps
                false // isDnsBucketNamingDisabled
        );

        url = new URL(signedGetUrl);
        conn = (HttpURLConnection) url.openConnection();
        assertEquals("text/plain", conn.getHeaderField("content-type"));
        assertEquals("latin1", conn.getHeaderField("content-encoding"));

        // Clean up.
        service.deleteObject(bucketName, object.getKey());
    } finally {
        cleanupBucketForTest("testUrlSigningUsingSignatureVersion4");
    }
}

From source file:org.samcrow.ridgesurvey.data.UploadService.java

/**
 * Uploads an observation/*from   w w  w .  j a v  a  2  s  .c  om*/
 *
 * @param observation the observation to upload
 */
private void upload(@NonNull URL url, @NonNull Observation observation)
        throws IOException, ParseException, UploadException {
    Objects.requireNonNull(observation);
    final Map<String, String> formData = formatObservation(observation);
    Log.v(TAG, "Formatted observation: " + formData);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {
        // Disable response compression, which might be causing problems
        connection.setRequestProperty("Accept-Encoding", "identity");
        // POST
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setChunkedStreamingMode(0);
        final PrintStream out = new PrintStream(connection.getOutputStream());
        writeFormEncodedData(formData, out);
        out.flush();

        final String response = IOUtils.toString(connection.getInputStream());
        Log.v(TAG, response);

        // Check status
        final int status = connection.getResponseCode();
        if (status == 200) {
            // Check for valid JSON
            final JSONObject json = new JSONObject(response);

            final String result = json.optString("result", "");
            if (!result.equals("success")) {
                final String message = json.optString("message", null);
                if (message != null) {
                    throw new UploadException(message);
                } else {
                    throw new UploadException("Unknown server error");
                }
            }
        } else if (status == 301 || status == 302) {
            // Handle redirect and add cookies
            final String location = connection.getHeaderField("Location");
            if (location != null) {
                final URL redirectUrl = new URL(location);
                Log.i(TAG, "Following redirect to " + redirectUrl);
                upload(redirectUrl, observation);
            } else {
                throw new UploadException("Got a 301 or 302 response with no Location header");
            }
        } else {
            throw new UploadException("Unexpected HTTP status " + status);
        }

    } catch (JSONException e) {
        final ParseException e1 = new ParseException("Failed to parse response JSON", 0);
        e1.initCause(e);
        throw e1;
    } finally {
        connection.disconnect();
    }
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;/* www .ja v a 2s. c o  m*/
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw new IOException(errorString);
        }

        result = readDataFromConnection(connection);
    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return (T) gson.fromJson(result, tClass);
}

From source file:uk.ac.vfb.geppetto.VFBProcessTermInfo.java

/**
 * @param urlString//from w  ww .j a va 2  s.  c  o  m
 */
private String checkURL(String urlString) {
    try {
        urlString = urlString.replace("https://", "http://").replace(":5000", "");
        urlString = urlString.replace("//virtualflybrain.org", "//www.virtualflybrain.org");
        URL url = new URL(urlString);
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        huc.setInstanceFollowRedirects(true);
        int response = huc.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            return urlString;
        } else if (response == HttpURLConnection.HTTP_MOVED_TEMP
                || response == HttpURLConnection.HTTP_MOVED_PERM) {
            return checkURL(huc.getHeaderField("Location"));
        }
        return null;
    } catch (Exception e) {
        System.out.println("Error checking url (" + urlString + ") " + e.toString());
        return null;
    }
}

From source file:com.wanikani.wklib.Connection.java

protected Response call(Meter meter, String resource, boolean isArray, String arg, CacheInfo cinfo)
        throws IOException {
    HttpURLConnection conn;
    JSONTokener tok;//w  ww.j  a  va  2 s  .  c  om
    InputStream is;
    URL url;

    url = new URL(makeURL(resource, arg));
    conn = null;
    tok = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        if (cinfo != null) {
            if (cinfo.etag != null)
                conn.setRequestProperty("If-None-Match", cinfo.etag);
            else if (cinfo.modified != null)
                conn.setIfModifiedSince(cinfo.modified.getTime());
        }
        setTimeouts(conn);
        conn.connect();
        if (cinfo != null && cinfo.hasData() && conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED)
            throw new NotModifiedException();
        measureHeaders(meter, conn, false);
        is = conn.getInputStream();
        tok = new JSONTokener(readStream(meter, is));
    } finally {
        if (conn != null)
            conn.disconnect();
    }

    if (cinfo != null) {
        cinfo.modified = new Date();
        if (conn.getDate() > 0)
            cinfo.modified = new Date(conn.getDate());
        if (conn.getLastModified() > 0)
            cinfo.modified = new Date(conn.getLastModified());

        cinfo.etag = conn.getHeaderField("ETag");
    }

    try {
        return new Response(new JSONObject(tok), isArray);
    } catch (JSONException e) {
        throw new ParseException();
    }
}