List of usage examples for java.net HttpURLConnection getRequestMethod
public String getRequestMethod()
From source file:pt.lsts.neptus.comm.iridium.HubIridiumMessenger.java
@Override public void sendMessage(IridiumMessage msg) throws Exception { byte[] data = msg.serialize(); data = new String(Hex.encodeHex(data)).getBytes(); URL u = new URL(messagesUrl); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true);/* w w w .j av a 2s . co m*/ conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/hub"); conn.setRequestProperty("Content-Length", String.valueOf(data.length * 2)); conn.setConnectTimeout(timeoutMillis); OutputStream os = conn.getOutputStream(); os.write(data); os.close(); InputStream is = conn.getInputStream(); ByteArrayOutputStream incoming = new ByteArrayOutputStream(); IOUtils.copy(is, incoming); is.close(); NeptusLog.pub().info("Sent " + msg.getClass().getSimpleName() + " through HTTP: " + conn.getResponseCode() + " " + conn.getResponseMessage()); try { logHubInteraction(msg.getClass().getSimpleName() + " (" + msg.getMessageType() + ")", messagesUrl, conn.getRequestMethod(), "" + conn.getResponseCode(), ByteUtil.encodeToHex(msg.serialize()), new String(incoming.toByteArray())); } catch (Exception e) { NeptusLog.pub().error(e); } if (conn.getResponseCode() != 200) { throw new Exception("Server returned " + conn.getResponseCode() + ": " + conn.getResponseMessage()); } }
From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java
protected String request(HttpMethod httpMethod, URL url, int timeout, IResource resource) throws SocketTimeoutException, HttpClientException { HttpURLConnection connection = null; try {/* w ww.ja va 2 s . c om*/ connection = createConnection(url, userAgent, acceptedVersion, acceptedMediaType, sslAuthorizationCallback, timeout); if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) { setContentTypeHeader(acceptedVersion, acceptedMediaType, connection); } // PATCH not yet supported by JVM setRequestMethod(httpMethod, connection); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Request Properties: %s", connection.getRequestProperties())); LOGGER.debug(String.format("Request Method: %s", connection.getRequestMethod())); } if (resource != null) { if (LOGGER.isDebugEnabled()) LOGGER.debug(resource.toJson(false)); connection.setDoOutput(true); PrintWriter writer = new PrintWriter(connection.getOutputStream()); writer.write(resource.toString()); writer.flush(); } return IOUtils.toString(connection.getInputStream(), "UTF-8"); } catch (SocketTimeoutException e) { throw e; } catch (IOException e) { throw createException(e, connection); } finally { disconnect(connection); } }
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();/*from w w w .j a va2 s . c om*/ 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: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 w w w . j av a 2 s . c om 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:org.kohsuke.github.Requester.java
private void setRequestMethod(HttpURLConnection uc) throws IOException { try {/* w w w .j a va 2s . c o m*/ uc.setRequestMethod(method); } catch (ProtocolException e) { // JDK only allows one of the fixed set of verbs. Try to override that try { Field $method = HttpURLConnection.class.getDeclaredField("method"); $method.setAccessible(true); $method.set(uc, method); } catch (Exception x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } // sun.net.www.protocol.https.DelegatingHttpsURLConnection delegates to another HttpURLConnection try { Field $delegate = uc.getClass().getDeclaredField("delegate"); $delegate.setAccessible(true); Object delegate = $delegate.get(uc); if (delegate instanceof HttpURLConnection) { HttpURLConnection nested = (HttpURLConnection) delegate; setRequestMethod(nested); } } catch (NoSuchFieldException x) { // no problem } catch (IllegalAccessException x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } } if (!uc.getRequestMethod().equals(method)) throw new IllegalStateException("Failed to set the request method to " + method); }
From source file:com.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(); 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 ww w . jav a 2s .com*/ 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<Request, 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:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException { T ret = null;// w w w . j av a2s. c om try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); } } catch (IOException ex) { IOUtils.closeStream(conn.getInputStream()); throw ex; } if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Ideally, this should happen only when there is an Authentication // failure. Unfortunately, the AuthenticationFilter returns 403 when it // cannot authenticate (Since a 401 requires Server to send // WWW-Authenticate header as well).. KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token(); if (authRetryCount > 0) { String contentType = conn.getRequestProperty(CONTENT_TYPE); String requestMethod = conn.getRequestMethod(); URL url = conn.getURL(); conn = createConnection(url, requestMethod); conn.setRequestProperty(CONTENT_TYPE, contentType); return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1); } } try { AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) { // Ignore the AuthExceptions.. since we are just using the method to // extract and set the authToken.. (Workaround till we actually fix // AuthenticatedURL properly to set authToken post initialization) } HttpExceptionUtils.validateResponse(conn, expectedResponse); if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) { ObjectMapper mapper = new ObjectMapper(); InputStream is = null; try { is = conn.getInputStream(); ret = mapper.readValue(is, klass); } finally { IOUtils.closeStream(is); } } return ret; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** */* ww w . j av a2s.com*/ * @param url * @param requestStr * @param messageContext * @return */ public String makeCreditRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); //Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.debug("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()); log.debug("Southbound Request Headers: " + connection.getRequestProperties()); log.debug("Southbound Request Body: " + requestStr); //UNICODE BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.debug("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage()); log.debug("Southbound Response Headers: " + connection.getHeaderFields()); log.debug("Southbound Response Body: " + retStr); } catch (Exception e) { log.error("[CreditRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * * @param url/*from w w w . j a v a2s . co m*/ * @param requestStr * @param messageContext * @return */ public String makeWalletRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { String retStr = ""; int statusCode = 0; URL neturl; HttpURLConnection connection = null; try { neturl = new URL(url); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8");//ADDED if (auth) { connection.setRequestProperty("Authorization", "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext)); //Add JWT token header org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; String jwtparam = (String) headersMap.get("x-jwt-assertion"); if (jwtparam != null) { connection.setRequestProperty("x-jwt-assertion", jwtparam); } } } if (inclueHeaders) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; Iterator it = headersMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids a ConcurrentModificationException } } } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); log.info("Southbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Request Headers: " + connection.getRequestProperties()); } log.info("Southbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext)); //========================UNICODE PATCH========================================= BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream()); wr.write(requestStr.getBytes("UTF-8")); wr.flush(); wr.close(); //========================UNICODE PATCH========================================= statusCode = connection.getResponseCode(); if ((statusCode != 200) && (statusCode != 201) && (statusCode != 400) && (statusCode != 401)) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } InputStream is = null; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); log.info("Southbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Southbound Response Headers: " + connection.getHeaderFields()); } log.info("Southbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } messageContext.setProperty(DataPublisherConstants.RESPONSE_CODE, Integer.toString(statusCode)); messageContext.setProperty(DataPublisherConstants.MSISDN, messageContext.getProperty(MSISDNConstants.USER_MSISDN)); publishWalletPaymentData(statusCode, retStr, messageContext); } return retStr; }