List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java
private String readResponseFromGetRequest(HttpURLConnection httpConnection) throws DeviceManagementException { BufferedReader bufferedReader = null; try {/*from w w w . j ava2 s. co m*/ bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); } catch (IOException e) { String errorMsg = "There is an issue with connecting the reader to the input stream at: " + httpConnection.getURL(); log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } String responseLine; StringBuffer completeResponse = new StringBuffer(); try { while ((responseLine = bufferedReader.readLine()) != null) { completeResponse.append(responseLine); } } catch (IOException e) { String errorMsg = "Error occured whilst trying read from the connection stream at: " + httpConnection.getURL(); log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } try { bufferedReader.close(); } catch (IOException e) { log.error("Could not succesfully close the bufferedReader to the connection at: " + httpConnection.getURL()); } return completeResponse.toString(); }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentUtilOperations.java
public static void refreshOAuthToken() throws AgentCoreOperationException { AgentManager agentManager = AgentManager.getInstance(); String tokenEndpoint = agentManager.getAgentConfigs().getApimGatewayEndpoint(); tokenEndpoint = tokenEndpoint + APIManagerTokenUtils.TOKEN_ENDPOINT; HttpURLConnection httpConnection = null; BufferedReader connectionBuffer = null; String requestPayload;//from w w w.jav a2 s.c om String dataFromBuffer; StringBuilder responseMessage = new StringBuilder(); try { String refreshToken = agentManager.getAgentConfigs().getRefreshToken(); String applicationScope = "device_type_" + AgentConstants.DEVICE_TYPE + " device_" + agentManager.getAgentConfigs().getDeviceId(); requestPayload = APIManagerTokenUtils.GRANT_TYPE + "=" + APIManagerTokenUtils.REFRESH_TOKEN + "&" + APIManagerTokenUtils.REFRESH_TOKEN + "=" + refreshToken + "&" + APIManagerTokenUtils.SCOPE + "=" + applicationScope; httpConnection = TransportUtils.getHttpConnection(tokenEndpoint); httpConnection.setRequestMethod(AgentConstants.HTTP_POST); httpConnection.setRequestProperty(AgentConstants.AUTHORIZATION_HEADER, "Basic " + agentManager.getAgentConfigs().getApiApplicationKey()); httpConnection.setRequestProperty(AgentConstants.CONTENT_TYPE_HEADER, AgentConstants.X_WWW_FORM_URLENCODED); httpConnection.setDoOutput(true); DataOutputStream dataOutPutWriter = new DataOutputStream(httpConnection.getOutputStream()); dataOutPutWriter.writeBytes(requestPayload); dataOutPutWriter.flush(); dataOutPutWriter.close(); log.info(AgentConstants.LOG_APPENDER + "Request to refresh OAuth token was sent to [" + httpConnection.getURL() + "] with payload [" + requestPayload + "]."); log.info(AgentConstants.LOG_APPENDER + "Response [" + httpConnection.getResponseCode() + ":" + httpConnection.getResponseMessage() + "] was received for token refresh attempt."); if (httpConnection.getResponseCode() == HttpStatus.OK_200) { connectionBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); while ((dataFromBuffer = connectionBuffer.readLine()) != null) { responseMessage.append(dataFromBuffer); } log.info(AgentConstants.LOG_APPENDER + "Response " + responseMessage + " was received for the token refresh call."); updateExistingTokens(responseMessage.toString()); } else if (httpConnection.getResponseCode() == HttpStatus.BAD_REQUEST_400) { log.error(AgentConstants.LOG_APPENDER + "Token refresh call returned with a [400 Bad Request].\nThe refresh-token has " + "probably expired.\nPlease contact System-Admin to get a valid refresh-token."); } else { log.warn(AgentConstants.LOG_APPENDER + "There was an issue with refreshing the Access Token."); } } catch (TransportHandlerException e) { throw new AgentCoreOperationException(e); } catch (ProtocolException e) { String errorMsg = "Protocol specific error occurred when trying to set method to " + AgentConstants.HTTP_POST + " for endpoint at: " + tokenEndpoint; log.error(AgentConstants.LOG_APPENDER + errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (IOException e) { String errorMsg = "An IO error occurred whilst trying to get the response code from: " + tokenEndpoint + " for a HTTP " + AgentConstants.HTTP_POST + " call."; log.error(AgentConstants.LOG_APPENDER + errorMsg); throw new AgentCoreOperationException(errorMsg, e); } finally { if (connectionBuffer != null) { try { connectionBuffer.close(); } catch (IOException e) { log.error(AgentConstants.LOG_APPENDER + "Error encounter whilst attempting to close buffer to connection at: " + tokenEndpoint); } } if (httpConnection != null) { httpConnection.disconnect(); } } }
From source file:grails.plugin.cloudfoundry.GrailsHttpRequestFactory.java
protected HttpURLConnection wrap(final HttpURLConnection connection) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HttpURLConnection.class); enhancer.setInterceptDuringConstruction(false); Callback callback = new MethodInterceptor() { @SuppressWarnings("hiding") public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { try { Object value = method.invoke(connection, args); if ("getInputStream".equals(method.getName())) { return wrap((InputStream) value); }/*from w ww. j a va 2 s. c om*/ return value; } catch (InvocationTargetException ex) { throw ex.getCause(); } } }; enhancer.setCallbacks(new Callback[] { callback }); enhancer.setCallbackTypes(new Class[] { callback.getClass() }); return (HttpURLConnection) enhancer.create(new Class[] { URL.class }, new Object[] { connection.getURL() }); }
From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java
@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); // First time we will have no cookies if (cookieManager.getCookieStore().getCookies().isEmpty() && shouldAttemptCookieRequest.get()) { if (!requestCookie(context)) { // Requesting a cookie failed, set a flag if we failed so we won't try again shouldAttemptCookieRequest.set(false); }/*from w w w . j a va2s . c om*/ } if (shouldAttemptCookieRequest.get()) { // Debug logging if (logger.isLoggable(Level.FINEST)) { logger.finest("Attempt to add cookie to request."); logger.finest("Cookies are stored for URIs: " + cookieManager.getCookieStore().getURIs()); } // Apply any saved cookies to the request try { Map<String, List<String>> requestCookieHeaders = cookieManager.get(connection.getURL().toURI(), connection.getRequestProperties()); for (Map.Entry<String, List<String>> requestCookieHeader : requestCookieHeaders.entrySet()) { List<String> cookies = requestCookieHeader.getValue(); if (cookies != null && !cookies.isEmpty()) { connection.setRequestProperty(requestCookieHeader.getKey(), listToSemicolonSeparatedString(cookies)); } else { logger.finest("No cookie values to set."); } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read request properties", e); } catch (URISyntaxException e) { logger.log(Level.SEVERE, "Failed to convert request URL to URI for cookie " + "retrieval."); } } return context; }
From source file:ai.grakn.engine.loader.client.LoaderClient.java
/** * Send an insert query to one host/*ww w . j a va 2s . c om*/ */ private String executePost(HttpURLConnection connection, String body) { try { // create post connection.setRequestMethod(REST.HttpConn.POST_METHOD); connection.addRequestProperty(REST.HttpConn.CONTENT_TYPE, REST.HttpConn.APPLICATION_POST_TYPE); // add body and execute connection.setRequestProperty(REST.HttpConn.CONTENT_LENGTH, Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes(REST.HttpConn.UTF8)); connection.getOutputStream().flush(); // get response return IOUtils.toString(connection.getInputStream()); } catch (HTTPException e) { LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(), e.getStatusCode(), getResponseMessage(connection))); } catch (IOException e) { LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString())); } finally { connection.disconnect(); } return null; }
From source file:com.trk.aboutme.facebook.Request.java
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection) throws IOException, JSONException { Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request"); int numRequests = requests.size(); HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST; connection.setRequestMethod(connectionHttpMethod.name()); 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();//w ww. j ava 2s .c o m return; } connection.setDoOutput(true); BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); try { Serializer serializer = new Serializer(outputStream, logger); if (numRequests == 1) { Request request = requests.get(0); logger.append(" Parameters:\n"); serializeParameters(request.parameters, serializer); logger.append(" Attachments:\n"); serializeAttachments(request.parameters, serializer); if (request.graphObject != null) { processGraphObject(request.graphObject, url.getPath(), serializer); } } else { String batchAppID = getBatchAppId(requests); if (Utility.isNullOrEmpty(batchAppID)) { throw new FacebookException("At least one request in a batch must have an open Session, or a " + "default app ID must be specified."); } serializer.writeString(BATCH_APP_ID_PARAM, batchAppID); // We write out all the requests as JSON, remembering which file attachments they have, then // write out the attachments. Bundle attachments = new Bundle(); serializeRequestsAsJSON(serializer, requests, attachments); logger.append(" Attachments:\n"); serializeAttachments(attachments, serializer); } } finally { outputStream.close(); } logger.log(); }
From source file:org.exoplatform.addon.pulse.service.ws.RestActivitiesStatistic.java
private String httpGet(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); LOG.debug("Calling API: " + conn.getURL()); if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); }/*from w ww .j a v a 2 s. c o m*/ // Buffer the result into a string BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); return sb.toString(); }
From source file:com.spotify.helios.client.DefaultRequestDispatcher.java
@Override public ListenableFuture<Response> request(final URI uri, final String method, final byte[] entityBytes, final Map<String, List<String>> headers) { return executorService.submit(new Callable<Response>() { @Override//from w w w . j ava2 s.com public Response call() throws Exception { final HttpURLConnection connection = connect(uri, method, entityBytes, headers); final int status = connection.getResponseCode(); final InputStream rawStream; if (status / 100 != 2) { rawStream = connection.getErrorStream(); } else { rawStream = connection.getInputStream(); } final boolean gzip = isGzipCompressed(connection); final InputStream stream = gzip ? new GZIPInputStream(rawStream) : rawStream; final ByteArrayOutputStream payload = new ByteArrayOutputStream(); if (stream != null) { int n; byte[] buffer = new byte[4096]; while ((n = stream.read(buffer, 0, buffer.length)) != -1) { payload.write(buffer, 0, n); } } URI realUri = connection.getURL().toURI(); if (log.isTraceEnabled()) { log.trace("rep: {} {} {} {} {} gzip:{}", method, realUri, status, payload.size(), decode(payload), gzip); } else { log.debug("rep: {} {} {} {} gzip:{}", method, realUri, status, payload.size(), gzip); } return new Response(method, uri, status, payload.toByteArray(), Collections.unmodifiableMap(Maps.newHashMap(connection.getHeaderFields()))); } private boolean isGzipCompressed(final HttpURLConnection connection) { final List<String> encodings = connection.getHeaderFields().get("Content-Encoding"); if (encodings == null) { return false; } for (String encoding : encodings) { if ("gzip".equals(encoding)) { return true; } } return false; } }); }
From source file:org.apache.cactus.client.authentication.FormAuthentication.java
/** * Get a cookie required to be set by set-cookie header field. * @param theConnection a {@link HttpURLConnection} * @param theTarget the target cookie name * @return the {@link Cookie}//from w w w . java2 s .co m */ private Cookie getCookie(HttpURLConnection theConnection, String theTarget) { // Check (possible multiple) cookies for a target. int i = 1; String key = theConnection.getHeaderFieldKey(i); while (key != null) { if (key.equalsIgnoreCase("set-cookie")) { // Cookie is in the form: // "NAME=VALUE; expires=DATE; path=PATH; // domain=DOMAIN_NAME; secure" // The only thing we care about is finding a cookie with // the name "JSESSIONID" and caching the value. String cookiestr = theConnection.getHeaderField(i); String nameValue = cookiestr.substring(0, cookiestr.indexOf(";")); int equalsChar = nameValue.indexOf("="); String name = nameValue.substring(0, equalsChar); String value = nameValue.substring(equalsChar + 1); if (name.equalsIgnoreCase(theTarget)) { return new Cookie(theConnection.getURL().getHost(), name, value); } } key = theConnection.getHeaderFieldKey(++i); } return null; }
From source file:org.broad.igv.util.HttpUtils.java
private void logHeaders(HttpURLConnection conn) { Map<String, List<String>> headerFields = conn.getHeaderFields(); log.debug("Headers for " + conn.getURL()); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { log.debug(header.getKey() + ": " + org.apache.commons.lang.StringUtils.join(header.getValue(), ',')); }/* www . j a v a 2 s .c o m*/ }