List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:com.BeatYourRecord.SubmitActivity.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem if (isFirstRequest()) { Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {/*from ww w . ja v a 2s. co m*/ urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); urlConnection.setRequestProperty("Content-Type", "video/3gpp"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range")); //////may be //log.v("id man id",urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; double percent = (totalBytesUploaded / currentFileSize) * 99; /* Log.d(LOG_TAG, String.format( "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, totalBytesUploaded, percent)); */ dialog.setProgress((int) percent); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(LOG_TAG, "responseCode=" + responseCode); Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); //log.v("Video ID", videoId); vidId = videoId; String latLng = null; if (this.videoLocation != null) { latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(), this.videoLocation.getLongitude()); } submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName, SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken, latLng, this.tags); dialog.setProgress(100); //log.v("10video id",videoId); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(LOG_TAG, String.format("Headers keys %s.", keys)); //////////////may be for (String key : keySet) { Log.d(LOG_TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(LOG_TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(LOG_TAG, error); // TODO - this exception will trigger retry mechanism to kick in // TODO - even though it should not, consider introducing a new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed succesfully Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }
From source file:com.cr_wd.android.network.HttpClient.java
/** * Performs a HTTP GET/POST Request//from w w w .j a v a 2s .co m * * @return id of the request */ protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params, final HttpHandler handler) { if (headers == null) { headers = new HttpHeaders(); } if (params == null) { params = new HttpParams(); } handler.client = this; final int requestId = incrementRequestId(); class HandlerRunnable extends Handler implements Runnable { private final Method method; private String url; private final HttpHeaders headers; private final HttpParams params; private final HttpHandler handler; private HttpResponse response; private boolean canceled = false; private int retries = 0; protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers, final HttpParams params, final HttpHandler handler) { this.method = method; this.url = url; this.headers = headers; this.params = params; this.handler = handler; } @Override public void run() { execute(); } private void execute() { response = new HttpResponse(requestId, method, url); HttpURLConnection conn = null; try { /* append query string for GET requests */ if (method == Method.GET) { if (!params.urlParams.isEmpty()) { url += ('?' + params.getParamString()); } } /* setup headers for POST requests */ if (method == Method.POST) { headers.addHeader("Accept-Charset", requestOptions.encoding); if (params.hasMultipartParams()) { final SimpleMultipart multipart = params.getMultipart(); headers.addHeader("Content-Type", multipart.getContentType()); } else { headers.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + requestOptions.encoding); } } if (canceled) { postCancel(); return; } /* open and configure the connection */ conn = (HttpURLConnection) new URL(url).openConnection(); postStart(); if (method == Method.GET) { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); } else if (method == Method.POST) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); } conn.setAllowUserInteraction(false); conn.setReadTimeout(requestOptions.readTimeout); conn.setConnectTimeout(requestOptions.connectTimeout); /* add headers to the connection */ for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) { for (final String value : entry.getValue()) { conn.addRequestProperty(entry.getKey(), value); } } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.requestProperties = conn.getRequestProperties(); /* do post */ if (method == Method.POST) { InputStream is; if (params.hasMultipartParams()) { is = params.getMultipart().getContent(); } else { is = new ByteArrayInputStream(params.getParamString().getBytes()); } final OutputStream os = conn.getOutputStream(); writeStream(os, is); } else { conn.connect(); } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.contentEncoding = conn.getContentEncoding(); response.contentLength = conn.getContentLength(); response.contentType = conn.getContentType(); response.date = conn.getDate(); response.expiration = conn.getExpiration(); response.headerFields = conn.getHeaderFields(); response.ifModifiedSince = conn.getIfModifiedSince(); response.lastModified = conn.getLastModified(); response.responseCode = conn.getResponseCode(); response.responseMessage = conn.getResponseMessage(); /* do get */ if (conn.getResponseCode() < 400) { response.responseBody = readStream(conn.getInputStream()); postSuccess(); } else { response.responseBody = readStream(conn.getErrorStream()); response.throwable = new Exception(response.responseMessage); postError(); } } catch (final Exception e) { if (retries < requestOptions.maxRetries) { retries++; postRetry(); execute(); } else { response.responseBody = e.getMessage(); response.throwable = e; postError(); } } finally { if (conn != null) { conn.disconnect(); } } } private String readStream(final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); final ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } return new String(baf.toByteArray()); } private void writeStream(final OutputStream os, final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } os.write(buffer, 0, read); } if (!canceled) { os.flush(); } try { os.close(); } catch (final IOException e) { } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } } @Override public void handleMessage(final Message msg) { if (msg.what == HttpHandler.MESSAGE_CANCEL) { canceled = true; } } private void postSuccess() { postMessage(HttpHandler.MESSAGE_SUCCESS); } private void postError() { postMessage(HttpHandler.MESSAGE_ERROR); } private void postCancel() { postMessage(HttpHandler.MESSAGE_CANCEL); } private void postStart() { postMessage(HttpHandler.MESSAGE_START); } private void postRetry() { postMessage(HttpHandler.MESSAGE_RETRY); } private void postMessage(final int what) { final Message msg = handler.obtainMessage(); msg.what = what; msg.arg1 = requestId; msg.obj = response; handler.sendMessage(msg); } } ; /* Create a new HandlerRunnable and start it */ final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler); requests.put(requestId, new WeakReference<Handler>(hr)); new Thread(hr).start(); /* Return with the request id */ return requestId; }
From source file:net.ymate.module.webproxy.WebProxy.java
@SuppressWarnings("unchecked") public void transmission(HttpServletRequest request, HttpServletResponse response, String url, Type.HttpMethod method) throws Exception { StopWatch _consumeTime = null;/*from ww w . j a va 2s. c o m*/ long _threadId = 0; if (_LOG.isDebugEnabled()) { _consumeTime = new StopWatch(); _consumeTime.start(); _threadId = Thread.currentThread().getId(); _LOG.debug("-------------------------------------------------"); _LOG.debug("--> [" + _threadId + "] URL: " + url); } // HttpURLConnection _conn = null; try { if (__moduleCfg.isUseProxy()) { _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy()); } else { _conn = (HttpURLConnection) new URL(url).openConnection(); } _conn.setUseCaches(__moduleCfg.isUseCaches()); _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects()); // boolean _postFlag = Type.HttpMethod.POST.equals(method); boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/"); if (_postFlag) { _conn.setDoOutput(true); _conn.setDoInput(true); _conn.setRequestMethod(method.name()); } if (__moduleCfg.getConnectTimeout() > 0) { _conn.setConnectTimeout(__moduleCfg.getConnectTimeout()); } if (__moduleCfg.getReadTimeout() > 0) { _conn.setReadTimeout(__moduleCfg.getReadTimeout()); } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Method: " + method.name()); _LOG.debug("--> [" + _threadId + "] Request Headers: "); } // Enumeration _header = request.getHeaderNames(); while (_header.hasMoreElements()) { String _name = (String) _header.nextElement(); String _value = request.getHeader(_name); boolean _flag = false; if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type") || __moduleCfg.isTransferHeaderEnabled() && (!__moduleCfg.getTransferHeaderBlackList().isEmpty() && !__moduleCfg.getTransferHeaderBlackList().contains(_name) || !__moduleCfg.getTransferHeaderWhiteList().isEmpty() && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) { _conn.setRequestProperty(_name, _value); _flag = true; } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value); } } _conn.connect(); // if (_postFlag) { DataOutputStream _output = new DataOutputStream(_conn.getOutputStream()); try { if (_multipartFlag) { if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Multipart: TRUE"); } IOUtils.copyLarge(request.getInputStream(), _output); } else { String _charset = request.getCharacterEncoding(); String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset); IOUtils.write(_queryStr, _output, _charset); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Request Parameters: "); Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true, _charset); for (Map.Entry<String, String> _param : _paramsMap.entrySet()) { _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": " + _param.getValue()); } } } _output.flush(); } finally { IOUtils.closeQuietly(_output); } } // int _code = _conn.getResponseCode(); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Code: " + _code); _LOG.debug("--> [" + _threadId + "] Response Headers: "); } // Map<String, List<String>> _headers = _conn.getHeaderFields(); for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) { if (_entry.getKey() != null) { boolean _flag = false; String _values = StringUtils.join(_entry.getValue(), ","); if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type") || __moduleCfg.isTransferHeaderEnabled() && !__moduleCfg.getResponseHeaderWhileList().isEmpty() && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) { response.setHeader(_entry.getKey(), _values); _flag = true; } if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": " + _values); } } } if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) { response.sendError(_code); } else { if (HttpURLConnection.HTTP_OK == _code) { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { if (!_multipartFlag) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody( _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else { IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody"); } } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.flushBuffer(); } else { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.setStatus(_code); response.flushBuffer(); } } } catch (Throwable e) { _LOG.warn("An exception occurred while processing request mapping '" + url + "': ", RuntimeUtils.unwrapThrow(e)); } finally { IOUtils.close(_conn); // if (_LOG.isDebugEnabled()) { if (_consumeTime != null) { _consumeTime.stop(); _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("-------------------------------------------------"); } } }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make north bound request./*from w ww . j a v a 2s.c o m*/ * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @param inclueHeaders * the inclue headers * @return the int */ public int makeNorthBoundRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { ICallresponse icallresponse = null; 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("Northbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Northbound Request Headers: " + connection.getRequestProperties()); } log.info("Northbound 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(); log.info("Northbound Response Status: " + statusCode + " " + connection.getResponseMessage() + " Request ID: " + UID.getRequestID(messageContext)); if (log.isDebugEnabled()) { log.debug("Northbound Response Headers: " + connection.getHeaderFields()); } log.info("Northbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext)); if (statusCode != 200) { throw new RuntimeException("Failed : HTTP error code : " + statusCode); } } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return 0; } finally { if (connection != null) { connection.disconnect(); } } return statusCode; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** */* w w w. j av a 2 s . c o m*/ * @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
/** * Make get request.// w ww .j a v a2s . co m * * @param operatorendpoint * the operatorendpoint * @param url * the url * @param requestStr * the request str * @param auth * the auth * @param messageContext * the message context * @return the string */ public String makeGetRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { int statusCode = 0; String retStr = ""; URL neturl; HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // DefaultHttpClient httpClient = new DefaultHttpClient(); String encurl = (requestStr != null) ? url + requestStr : url; neturl = new URL(encurl); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); 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); 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)); 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(); } } return retStr; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
public String makeRetrieveSMSGetRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth, MessageContext messageContext, boolean inclueHeaders) { Gson gson = new GsonBuilder().serializeNulls().create(); int statusCode = 0; String retStr = ""; URL neturl;//from ww w .ja v a 2 s. co m HttpURLConnection connection = null; try { // String Authtoken = AccessToken; // //FileUtil.getApplicationProperty("wow.api.bearer.token"); // DefaultHttpClient httpClient = new DefaultHttpClient(); String encurl = (requestStr != null) ? url + requestStr : url; neturl = new URL(encurl); connection = (HttpURLConnection) neturl.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); 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); 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)); 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)); SouthboundRetrieveResponse sbRetrieveResponse = gson.fromJson(retStr, SouthboundRetrieveResponse.class); if (sbRetrieveResponse != null && sbRetrieveResponse.getInboundSMSMessageList() != null) { if (sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage() != null && sbRetrieveResponse.getInboundSMSMessageList().getInboundSMSMessage().length != 0) { InboundSMSMessage[] inboundSMSMessageResponses = sbRetrieveResponse.getInboundSMSMessageList() .getInboundSMSMessage(); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(inboundSMSMessageResponses.length)); } else { InboundSMSMessage[] inboundSMSMessageResponses = new InboundSMSMessage[0]; InboundSMSMessageList inboundSMSMessageList = new InboundSMSMessageList(); inboundSMSMessageList.setInboundSMSMessage(inboundSMSMessageResponses); inboundSMSMessageList.setNumberOfMessagesInThisBatch("0"); inboundSMSMessageList.setResourceURL("Not Available"); inboundSMSMessageList.setTotalNumberOfPendingMessages("0"); sbRetrieveResponse.setInboundSMSMessageList(inboundSMSMessageList); InboundSMSMessage[] inboundSMSMessageResponsesN = sbRetrieveResponse.getInboundSMSMessageList() .getInboundSMSMessage(); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(inboundSMSMessageResponsesN.length)); } } else { messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(0)); } } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); messageContext.setProperty(DataPublisherConstants.RESPONSE, String.valueOf(0)); return null; } finally { if (connection != null) { connection.disconnect(); } } return retStr; }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
public Bitmap openRequestForBitmap(String url, RequestMethod requestMethod, Object paramObject) { if (!this.checkNetWork()) { // return this.notNetError; }//ww w. j a va 2s . c om HttpURLConnection conn = null; InputStream inputStream = null; Bitmap bitmap = null; try { // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "Begin a request--->>>>>>>>>>"); // } // try { // url = URLEncoder.encode(url, HttpConstant.ENCODE); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if (requestMethod == requestMethod.GET && paramObject != null) { // try { url = url + "?" + this.encodeUrlParam(paramObject); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // http://192.168.15.204:82/agcom/rest/roadRest/getBestRoad?id=2&xy=56536.156809,13853.484204 // 56364.173164,12955.347386 } // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "url:", url); LogUtil.info(this, "requestMethod:", requestMethod); LogUtil.info(this, "paramObject:", paramObject); // } // url = url.replace(" ", "%20"); conn = (HttpURLConnection) new URL(url).openConnection(); // System.out // .println("this.sessionStr == null" + this.sessionStr == null); // System.out.println(this.sessionStr == null); if (this.sessionStr != null) { conn.setRequestProperty("cookie", sessionStr); } conn.setConnectTimeout(5 * 1000); if (requestMethod == RequestMethod.GET) { // conn.setRequestMethod(method); // if (isMultipart) { // conn.setRequestProperty("Content-Type", // "multipart/form-data;"); // } else { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // } conn.connect(); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setUseCaches(false); // http: // // 192.168.16.16:8089/agcom/rest/system/locateDiscode/231/10// // Content-Type // if (isMultipart) { // conn.setRequestProperty("Content-Type", // "multipart/form-data;"); // } else { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // } // conn.setRequestProperty("Content-Type", // "application/x-www-form-urlencode"); // conn.connect(); if (paramObject != null) { conn.getOutputStream().write(this.encodeUrlParam(paramObject).getBytes("GBK")); } } inputStream = conn.getInputStream(); // in = new BufferedInputStream(uRLConnection // .getInputStream()); bitmap = BitmapFactory.decodeStream(inputStream); // response = read(inputStream); // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "response:", bitmap == null); // } if (this.sessionStr == null) { Map<String, List<String>> cookies = conn.getHeaderFields(); // this.cookieHeader = conn.getg for (String key : cookies.keySet()) { // System.out.println("sdfdsfd:" + key); if (key == null) { continue; } if ("set-cookie".equals(key.toLowerCase())) { List<String> values = cookies.get(key); String sessionStrTemp = ""; for (String value : values) { sessionStrTemp += value; sessionStrTemp += ";"; // conn.addRequestProperty("set-cookie", string); } // loginSessionStrTemp = // loginSessionStrTemp.substring(0, // loginSessionStrTemp.length() - 1); // System.out.println("loginSessionStrTemp:" // + loginSessionStrTemp); this.sessionStr = sessionStrTemp; this.sessionKey = key; // OldHttpUtil.LOGINSESSIONSTR = sessionStrTemp; // BaseHttpManager.sessionStr = loginSessionStrTemp; break; } } // System.out.println("sessionStr:" + sessionStr); } // System.out.println("openUrl:response:" + response); } catch (Exception e) { // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "End a request with exception below---XXXXXXXXXX"); // } e.printStackTrace(); return bitmap; } finally { if (conn != null) { conn.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "End a request successfully---VVVVVVVVVV"); // } return bitmap; }