Example usage for java.net HttpURLConnection getURL

List of usage examples for java.net HttpURLConnection getURL

Introduction

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

Prototype

public URL getURL() 

Source Link

Document

Returns the value of this URLConnection 's URL field.

Usage

From source file:eionet.cr.harvest.PullHarvest.java

/**
 * Returns RDF format from url connection.
 *
 * @param contentType/*  ww w  . jav  a2 s .  c om*/
 * @return
 */
private RDFFormat getRdfFormat(HttpURLConnection urlConn) {
    String contentType = getSourceContentType(urlConn);

    if (contentType == null) {
        return null;
    }

    if (contentType.equals(CONTENT_TYPE_TEXT)) {
        String path = urlConn.getURL().getPath();
        String[] arr = path.split("\\.");
        if (arr.length > 0) {
            String ext = arr[arr.length - 1];
            if (StringUtils.isNotEmpty(ext)) {
                if (ext.equalsIgnoreCase(EXT_TTL)) {
                    return RDFFormat.TURTLE;
                }
                if (ext.equalsIgnoreCase(EXT_N3)) {
                    return RDFFormat.N3;
                }
            }
        }
    }

    return RDFMediaTypes.toRdfFormat(contentType);
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.communication.http.FireAlarmHTTPCommincator.java

private void executeDataPush(String pushDataPayload) {
    AgentManager agentManager = AgentManager.getInstance();
    int responseCode = -1;
    String pushDataEndPointURL = agentManager.getPushDataAPIEP();
    HttpURLConnection httpConnection = null;

    try {// www . jav  a2  s. com
        httpConnection = TransportUtils.getHttpConnection(agentManager.getPushDataAPIEP());
        httpConnection.setRequestMethod(AgentConstants.HTTP_POST);
        httpConnection.setRequestProperty("Authorization",
                "Bearer " + agentManager.getAgentConfigs().getAuthToken());
        httpConnection.setRequestProperty("Content-Type", AgentConstants.APPLICATION_JSON_TYPE);

        httpConnection.setDoOutput(true);
        DataOutputStream dataOutPutWriter = new DataOutputStream(httpConnection.getOutputStream());
        dataOutPutWriter.writeBytes(pushDataPayload);
        dataOutPutWriter.flush();
        dataOutPutWriter.close();

        responseCode = httpConnection.getResponseCode();
        httpConnection.disconnect();

        log.info(AgentConstants.LOG_APPENDER + "Message - '" + pushDataPayload
                + "' was published to server at: " + httpConnection.getURL());

    } catch (ProtocolException exception) {
        String errorMsg = "Protocol specific error occurred when trying to set method to "
                + AgentConstants.HTTP_POST + " for:" + pushDataEndPointURL;
        log.error(AgentConstants.LOG_APPENDER + errorMsg);

    } catch (IOException exception) {
        String errorMsg = "An IO error occurred whilst trying to get the response code from: "
                + pushDataEndPointURL + " for a " + AgentConstants.HTTP_POST + " " + "method.";
        log.error(AgentConstants.LOG_APPENDER + errorMsg);

    } catch (TransportHandlerException exception) {
        log.error(AgentConstants.LOG_APPENDER + "Error encountered whilst trying to create HTTP-Connection "
                + "to IoT-Server EP at: " + pushDataEndPointURL);
    }

    if (responseCode == HttpStatus.CONFLICT_409 || responseCode == HttpStatus.PRECONDITION_FAILED_412) {
        log.warn(AgentConstants.LOG_APPENDER + "DeviceIP is being Re-Registered due to Push-Data failure "
                + "with response code: " + responseCode);
        registerThisDevice();

    } else if (responseCode != HttpStatus.NO_CONTENT_204) {
        if (log.isDebugEnabled()) {
            log.error(AgentConstants.LOG_APPENDER + "Status Code: " + responseCode
                    + " encountered whilst trying to Push-Device-Data to IoT " + "Server at: "
                    + agentManager.getPushDataAPIEP());
        }
        agentManager.updateAgentStatus(AgentConstants.SERVER_NOT_RESPONDING);
    }

    if (log.isDebugEnabled()) {
        log.debug(AgentConstants.LOG_APPENDER + "Push-Data call with payload - " + pushDataPayload
                + ", to IoT Server returned status " + responseCode);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.http.FireAlarmHTTPCommunicator.java

private void executeDataPush(String pushDataPayload) {
    AgentManager agentManager = AgentManager.getInstance();
    String pushDataEndPointURL = agentManager.getPushDataAPIEP();
    HttpURLConnection httpConnection;
    int responseCode = -1;

    try {/*from   w w  w .ja  va2s. c  o  m*/
        httpConnection = TransportUtils.getHttpConnection(agentManager.getPushDataAPIEP());
        httpConnection.setRequestMethod(AgentConstants.HTTP_POST);
        httpConnection.setRequestProperty("Authorization",
                "Bearer " + agentManager.getAgentConfigs().getAuthToken());
        httpConnection.setRequestProperty("Content-Type", AgentConstants.APPLICATION_JSON);

        httpConnection.setDoOutput(true);
        DataOutputStream dataOutPutWriter = new DataOutputStream(httpConnection.getOutputStream());
        dataOutPutWriter.writeBytes(pushDataPayload);
        dataOutPutWriter.flush();
        dataOutPutWriter.close();

        responseCode = httpConnection.getResponseCode();
        httpConnection.disconnect();

        log.info(AgentConstants.LOG_APPENDER + "Message - '" + pushDataPayload
                + "' was published to server at: " + httpConnection.getURL());

    } catch (ProtocolException exception) {
        String errorMsg = "Protocol specific error occurred when trying to set method to "
                + AgentConstants.HTTP_POST + " for:" + pushDataEndPointURL;
        log.error(AgentConstants.LOG_APPENDER + errorMsg);

    } catch (IOException exception) {
        String errorMsg = "An IO error occurred whilst trying to get the response code from: "
                + pushDataEndPointURL + " for a " + AgentConstants.HTTP_POST + " method.";
        log.error(AgentConstants.LOG_APPENDER + errorMsg);

    } catch (TransportHandlerException exception) {
        log.error(AgentConstants.LOG_APPENDER
                + "Error encountered whilst trying to create HTTP-Connection to IoT-Server EP at: "
                + pushDataEndPointURL);
    }

    if (responseCode == HttpStatus.CONFLICT_409 || responseCode == HttpStatus.PRECONDITION_FAILED_412) {
        log.warn(AgentConstants.LOG_APPENDER
                + "DeviceIP is being Re-Registered due to Push-Data failure with response code: "
                + responseCode);
        registerThisDevice();

    } else if (responseCode != HttpStatus.NO_CONTENT_204) {
        if (log.isDebugEnabled()) {
            log.error(AgentConstants.LOG_APPENDER + "Status Code: " + responseCode
                    + " encountered whilst trying to Push-Device-Data to IoT Server at: "
                    + agentManager.getPushDataAPIEP());
        }
        agentManager.updateAgentStatus(AgentConstants.SERVER_NOT_RESPONDING);
    }

    if (log.isDebugEnabled()) {
        log.debug(AgentConstants.LOG_APPENDER + "Push-Data call with payload - " + pushDataPayload
                + ", to IoT Server returned status " + responseCode);
    }
}

From source file:com.facebook.GraphRequest.java

final static void serializeToUrlConnection(GraphRequestBatch requests, HttpURLConnection connection)
        throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();
    boolean shouldUseGzip = isGzipCompressible(requests);

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());
    setConnectionContentType(connection, shouldUseGzip);

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or
    // HttpURLConnection will turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();//from   www  . ja va 2  s  .  c o m
        return;
    }

    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(connection.getOutputStream());
        if (shouldUseGzip) {
            outputStream = new GZIPOutputStream(outputStream);
        }

        if (hasOnProgressCallbacks(requests)) {
            ProgressNoopOutputStream countingStream = null;
            countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
            processRequest(requests, null, numRequests, url, countingStream, shouldUseGzip);

            int max = countingStream.getMaxProgress();
            Map<GraphRequest, RequestProgress> progressMap = countingStream.getProgressMap();

            outputStream = new ProgressOutputStream(outputStream, requests, progressMap, max);
        }

        processRequest(requests, logger, numRequests, url, outputStream, shouldUseGzip);
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    logger.log();
}

From source file:de.gebatzens.sia.SiaAPI.java

public APIResponse doRequest(String url, JSONObject request) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(BuildConfig.BACKEND_SERVER + url).openConnection();

    con.setRequestProperty("User-Agent",
            "SchulinfoAPP/" + BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + " "
                    + BuildConfig.BUILD_TYPE + " Android " + Build.VERSION.RELEASE + " " + Build.PRODUCT + ")");
    con.setRequestProperty("Accept-Encoding", "gzip");
    con.setConnectTimeout(3000);//from ww  w.j av  a2  s.  c om
    con.setRequestMethod(request == null ? "GET" : "POST");
    con.setInstanceFollowRedirects(false);

    if (request != null) {
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(request.toString());
        wr.flush();
        wr.close();
    }

    if (BuildConfig.DEBUG)
        Log.d("ggvp", "connection to " + con.getURL() + " established");

    InputStream in = con.getResponseCode() != 200 ? con.getErrorStream() : con.getInputStream();
    String encoding = con.getHeaderField("Content-Encoding");
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        in = new GZIPInputStream(in);
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String response = "";
    String line = "";
    while ((line = reader.readLine()) != null)
        response += line;
    JSONObject json = null;
    try {
        json = new JSONObject(response);
        String state = json.getString("state");
        Object data = json.opt("data");
        String reason = json.optString("reason", "");

        Log.d("ggvp", "received state " + state + " " + con.getResponseCode() + " reason: " + reason);

        return new APIResponse(state.equals("succeeded") ? APIState.SUCCEEDED : APIState.FAILED, data, reason);

    } catch (JSONException e) {
        Log.e("ggvp", e.toString());
        e.printStackTrace();
        return new APIResponse(APIState.FAILED);
    }

}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param connection/*from  w w  w .  ja va 2 s .c o  m*/
 * @return
 * @throws MalformedURLException
 */
private String getRedirectUrl(HttpURLConnection connection) throws MalformedURLException {

    String location = connection.getHeaderField("Location");
    if (location != null) {
        try {
            // If location does not seem to be an absolute URI, consider it relative to the
            // URL of this URL connection.
            if (!(new URI(location).isAbsolute())) {
                location = new URL(connection.getURL(), location).toString();
            }
        } catch (URISyntaxException e) {
            // Ignoring on purpose.
        }

        // we want to avoid fragment parts in CR harvest source URLs
        location = StringUtils.substringBefore(location, "#");
    }

    return location;
}

From source file:org.sipfoundry.sipxivr.rest.RestfulRequest.java

/**
 *  Perform the method on the URLConnection
 *
 * @param method  GET, POST, PUT, DELETE, etc.
 * @param urlConn a HttpURLConnection from {@link getConnection}
 * @return true on valid response, false on failure
 * @throws Exception/*from w w  w .j av  a  2  s .  c om*/
 */
public boolean request(String method, HttpURLConnection urlConn) throws Exception {
    if (urlConn == null) {
        throw new Exception("Invalid connection reference");
    }

    if (m_justTesting) {
        // Don't do anything if we are just in a test situation
        m_content = m_testingResult;
        return true;
    }

    try {
        // Let the RTS know that we want to do both input and output.
        urlConn.setDoOutput(true);
        urlConn.setDoInput(true);

        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        urlConn.setRequestMethod(method);

        // Connect!
        urlConn.connect();

        // Find out what happened
        m_responseCode = urlConn.getResponseCode();
        m_response = urlConn.getResponseMessage();

        LOG.info(String.format("RestfulRequest::request %s to %s response: %d", method, m_urlString,
                m_responseCode));

        if (m_responseCode < 200 || m_responseCode >= 300) {
            // Responses 200-299 are Okay, all other are suspect
            return false;
        }

        return true;
    }

    catch (Exception ex) {
        m_exception = ex;
        LOG.error(String.format("RestfulRequest::request %s to '%s' trouble '%s'", method,
                urlConn.getURL().toString(), urlConn.getResponseMessage()), ex);
    }
    return false;
}

From source file:net.caseif.flint.steel.lib.net.gravitydevelopment.updater.Updater.java

private URL followRedirects(String location) throws IOException {
    URL resourceUrl, base, next;//from   w ww .j a  v  a 2  s .  c  om
    HttpURLConnection conn;
    String redLoc;
    while (true) {
        resourceUrl = new URL(location);
        conn = (HttpURLConnection) resourceUrl.openConnection();

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0...");

        switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
            redLoc = conn.getHeaderField("Location");
            base = new URL(location);
            next = new URL(base, redLoc); // Deal with relative URLs
            location = next.toExternalForm();
            continue;
        }
        break;
    }
    return conn.getURL();
}

From source file:com.flyingspaniel.nava.request.Request.java

protected void doAuth(HttpURLConnection conn) {
    headersMMap.remove(AUTHORIZATION); // remove???
    Map authMap = options.getMap("auth", false);
    if (authMap != null) {
        String user = Hash.getString(authMap, "user");
        String pass = Hash.getString(authMap, "pass");
        if (Hash.getBoolean(authMap, "sendImmediately", false)) { // must be basic
            String encodedCredential = Base64Coder.encodeString(user + ":" + pass);
            headersMMap.add(AUTHORIZATION, BASIC_ + encodedCredential);
        } else if (response401 != null) {
            String challenge = response401.connection.getHeaderField("WWW-Authenticate");
            if (challenge.startsWith(BASIC_)) {
                String encodedCredential = Base64Coder.encodeString(user + ":" + pass);
                headersMMap.add(AUTHORIZATION, BASIC_ + encodedCredential);
            } else if (challenge.startsWith(DIGEST_)) {
                JRFC2617 authenticator = new JRFC2617(challenge);
                String path = conn.getURL().getPath();
                String encodedCredential = authenticator.createResponse(user, pass, null, method.name(), path);
                headersMMap.setFieldValuePairs(AUTHORIZATION, DIGEST_ + encodedCredential);
            } else
                throw new UnsupportedOperationException(challenge);
        }/*w w  w .j  a v  a2  s.c  o m*/
    }
}