List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(String str, String str2);
From source file:com.lxh.util.http.LXH_HttpClient.java
protected void sendRequest(Context mContext, DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, LXH_HttpResponseHandler responseHandler, Context context) {/*from w w w .j a v a2s.c o m*/ if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool .submit(new LXH_HttpRequest(context, client, httpContext, uriRequest, responseHandler)); if (context != null) { // Add request to request map List<WeakReference<Future<?>>> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList<WeakReference<Future<?>>>(); requestMap.put(context, requestList); } requestList.add(new WeakReference<Future<?>>(request)); // TODO: Remove dead weakrefs from requestLists? } }
From source file:com.nutsuser.ridersdomain.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, HttpPost, HttpGet, HttpPut, etc. *///from ww w.j a va 2 s. com protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, AsyncHttpResponseHandler responseHandler, Context context) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler)); if (context != null) { // Add request to request map List<WeakReference<Future<?>>> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList<WeakReference<Future<?>>>(); requestMap.put(context, requestList); } requestList.add(new WeakReference<Future<?>>(request)); // TODO: Remove dead weakrefs from requestLists? } return new RequestHandle(request); }
From source file:com.mike.aframe.http.KJHttp.java
/** * ??//w w w .j a v a2 s.c om * * @param client * httpClient * @param callback * Http? * @param context */ protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, HttpCallBack callback, Context context) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, callback)); if (context != null) { // List<WeakReference<Future<?>>> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList<WeakReference<Future<?>>>(); requestMap.put(context, requestList); } requestList.add(new WeakReference<Future<?>>(request)); } }
From source file:org.fao.geonet.api.records.formatters.FormatterApi.java
private String getXmlFromUrl(ServiceContext context, String lang, String url, WebRequest request) throws IOException, URISyntaxException { String adjustedUrl = url;/*from w w w .ja v a 2 s. c o m*/ if (!url.startsWith("http")) { adjustedUrl = context.getBean(SettingManager.class).getSiteURL(lang) + url; } else { final URI uri = new URI(url); Set allowedRemoteHosts = context.getApplicationContext().getBean("formatterRemoteFormatAllowedHosts", Set.class); Assert.isTrue(allowedRemoteHosts.contains(uri.getHost()), "xml.format is not allowed to make requests to " + uri.getHost()); } HttpUriRequest getXmlRequest = new HttpGet(adjustedUrl); final Iterator<String> headerNames = request.getHeaderNames(); while (headerNames.hasNext()) { String headerName = headerNames.next(); final String[] headers = request.getHeaderValues(headerName); for (String header : headers) { getXmlRequest.addHeader(headerName, header); } } GeonetHttpRequestFactory requestFactory = context.getBean(GeonetHttpRequestFactory.class); final ClientHttpResponse execute = requestFactory.execute(getXmlRequest); if (execute.getRawStatusCode() != 200) { throw new IllegalArgumentException("Request " + adjustedUrl + " did not succeed. Response Status: " + execute.getStatusCode() + ", status text: " + execute.getStatusText()); } return new String(ByteStreams.toByteArray(execute.getBody()), Constants.CHARSET); }
From source file:org.dasein.cloud.azure.AzureMethod.java
public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull String resource) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + resource + ")"); }/* w w w .ja va 2 s .c o m*/ if (wire.isDebugEnabled()) { wire.debug( "--------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(endpoint + account + resource); //get.addHeader("Content-Type", "application/xml"); get.addHeader("x-ms-version", "2012-03-01"); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("get(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (wire.isDebugEnabled()) { wire.debug("---> Binary Data <---"); } wire.debug(""); return input; } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + endpoint + account + resource); } } }
From source file:cn.rongcloud.im.server.network.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *//* www . j a va2 s . c om*/ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); Future<?> request = threadPool .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler)); if (context != null) { // Add request to request map List<WeakReference<Future<?>>> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList<WeakReference<Future<?>>>(); requestMap.put(context, requestList); } requestList.add(new WeakReference<Future<?>>(request)); // TODO: Remove dead weakrefs from requestLists? } return new RequestHandle(request); }
From source file:org.dasein.cloud.azure.AzureMethod.java
public @Nullable Document getAsXML(@Nonnull String account, @Nonnull URI uri) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")"); }/*from w w w. j av a 2 s. c om*/ if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); wire.debug(""); } try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); //get.addHeader("Content-Type", "application/xml"); if (uri.toString().indexOf("/services/images") > -1) { get.addHeader("x-ms-version", "2012-08-01"); } else { get.addHeader("x-ms-version", "2012-03-01"); } if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("get(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } return parseResponse(input, true); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); } } }
From source file:com.fujitsu.dc.core.rs.box.DcEngineSvcCollectionResource.java
/** * relay??./*from w w w.jav a2 s .com*/ * @param method * @param uriInfo URI * @param path ?? * @param headers * @param is * @return JAX-RS Response */ public Response relaycommon(String method, UriInfo uriInfo, String path, HttpHeaders headers, InputStream is) { String cellName = this.davRsCmp.getCell().getName(); String boxName = this.davRsCmp.getBox().getName(); String requestUrl = String.format("http://%s:%s/%s/%s/%s/service/%s", DcCoreConfig.getEngineHost(), DcCoreConfig.getEnginePort(), DcCoreConfig.getEnginePath(), cellName, boxName, path); // baseUrl? String baseUrl = uriInfo.getBaseUri().toString(); // ??? HttpClient client = new DefaultHttpClient(); HttpUriRequest req = null; if (method.equals(HttpMethod.POST)) { HttpPost post = new HttpPost(requestUrl); InputStreamEntity ise = new InputStreamEntity(is, -1); ise.setChunked(true); post.setEntity(ise); req = post; } else if (method.equals(HttpMethod.PUT)) { HttpPut put = new HttpPut(requestUrl); InputStreamEntity ise = new InputStreamEntity(is, -1); ise.setChunked(true); put.setEntity(ise); req = put; } else if (method.equals(HttpMethod.DELETE)) { HttpDelete delete = new HttpDelete(requestUrl); req = delete; } else { HttpGet get = new HttpGet(requestUrl); req = get; } req.addHeader("X-Baseurl", baseUrl); req.addHeader("X-Request-Uri", uriInfo.getRequestUri().toString()); // ?INDEXIDTYPE? if (davCmp instanceof DavCmpEsImpl) { DavCmpEsImpl test = (DavCmpEsImpl) davCmp; req.addHeader("X-Dc-Es-Index", test.getEsColType().getIndex().getName()); req.addHeader("X-Dc-Es-Id", test.getNodeId()); req.addHeader("X-Dc-Es-Type", test.getEsColType().getType()); req.addHeader("X-Dc-Es-Routing-Id", this.davRsCmp.getCell().getId()); req.addHeader("X-Dc-Box-Schema", this.davRsCmp.getBox().getSchema()); } // ??? MultivaluedMap<String, String> multivalueHeaders = headers.getRequestHeaders(); for (Iterator<Entry<String, List<String>>> it = multivalueHeaders.entrySet().iterator(); it.hasNext();) { Entry<String, List<String>> entry = it.next(); String key = (String) entry.getKey(); if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { continue; } List<String> valueList = (List<String>) entry.getValue(); for (Iterator<String> i = valueList.iterator(); i.hasNext();) { String value = (String) i.next(); req.setHeader(key, value); } } if (log.isDebugEnabled()) { log.debug("?EngineRelay " + req.getMethod() + " " + req.getURI()); Header[] reqHeaders = req.getAllHeaders(); for (int i = 0; i < reqHeaders.length; i++) { log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue()); } } // Engine?? HttpResponse objResponse = null; try { objResponse = client.execute(req); } catch (ClientProtocolException e) { throw DcCoreException.ServiceCollection.SC_INVALID_HTTP_RESPONSE_ERROR; } catch (Exception ioe) { throw DcCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe); } // ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode()); Header[] headersResEngine = objResponse.getAllHeaders(); // ? for (int i = 0; i < headersResEngine.length; i++) { // Engine????Transfer-Encoding???? // ?MW????????Content-Length???Transfer-Encoding???? // 2?????????????????????? if ("Transfer-Encoding".equalsIgnoreCase(headersResEngine[i].getName())) { continue; } // Engine????Date???? // Web??MW?Jetty???2????????? if (HttpHeaders.DATE.equalsIgnoreCase(headersResEngine[i].getName())) { continue; } res.header(headersResEngine[i].getName(), headersResEngine[i].getValue()); } InputStream isResBody = null; // ? HttpEntity entity = objResponse.getEntity(); if (entity != null) { try { isResBody = entity.getContent(); } catch (IllegalStateException e) { throw DcCoreException.ServiceCollection.SC_UNKNOWN_ERROR.reason(e); } catch (IOException e) { throw DcCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(e); } final InputStream isInvariable = isResBody; // ?? StreamingOutput strOutput = new StreamingOutput() { @Override public void write(final OutputStream os) throws IOException { int chr; try { while ((chr = isInvariable.read()) != -1) { os.write(chr); } } finally { isInvariable.close(); } } }; res.entity(strOutput); } // ?? return res.build(); }
From source file:io.personium.core.rs.box.PersoniumEngineSvcCollectionResource.java
/** * relay??./*from ww w . ja v a2s .c om*/ * @param method * @param uriInfo URI * @param path ?? * @param headers * @param is * @return JAX-RS Response */ public Response relaycommon(String method, UriInfo uriInfo, String path, HttpHeaders headers, InputStream is) { String cellName = this.davRsCmp.getCell().getName(); String boxName = this.davRsCmp.getBox().getName(); String requestUrl = String.format("http://%s:%s/%s/%s/%s/service/%s", PersoniumUnitConfig.getEngineHost(), PersoniumUnitConfig.getEnginePort(), PersoniumUnitConfig.getEnginePath(), cellName, boxName, path); // baseUrl? String baseUrl = uriInfo.getBaseUri().toString(); // ??? HttpClient client = new DefaultHttpClient(); HttpUriRequest req = null; if (method.equals(HttpMethod.POST)) { HttpPost post = new HttpPost(requestUrl); InputStreamEntity ise = new InputStreamEntity(is, -1); ise.setChunked(true); post.setEntity(ise); req = post; } else if (method.equals(HttpMethod.PUT)) { HttpPut put = new HttpPut(requestUrl); InputStreamEntity ise = new InputStreamEntity(is, -1); ise.setChunked(true); put.setEntity(ise); req = put; } else if (method.equals(HttpMethod.DELETE)) { HttpDelete delete = new HttpDelete(requestUrl); req = delete; } else { HttpGet get = new HttpGet(requestUrl); req = get; } req.addHeader("X-Baseurl", baseUrl); req.addHeader("X-Request-Uri", uriInfo.getRequestUri().toString()); if (davCmp instanceof DavCmpFsImpl) { DavCmpFsImpl dcmp = (DavCmpFsImpl) davCmp; req.addHeader("X-Personium-Fs-Path", dcmp.getFsPath()); req.addHeader("X-Personium-Fs-Routing-Id", dcmp.getCellId()); } req.addHeader("X-Personium-Box-Schema", this.davRsCmp.getBox().getSchema()); // ??? MultivaluedMap<String, String> multivalueHeaders = headers.getRequestHeaders(); for (Iterator<Entry<String, List<String>>> it = multivalueHeaders.entrySet().iterator(); it.hasNext();) { Entry<String, List<String>> entry = it.next(); String key = (String) entry.getKey(); if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { continue; } List<String> valueList = (List<String>) entry.getValue(); for (Iterator<String> i = valueList.iterator(); i.hasNext();) { String value = (String) i.next(); req.setHeader(key, value); } } if (log.isDebugEnabled()) { log.debug("?EngineRelay " + req.getMethod() + " " + req.getURI()); Header[] reqHeaders = req.getAllHeaders(); for (int i = 0; i < reqHeaders.length; i++) { log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue()); } } // Engine?? HttpResponse objResponse = null; try { objResponse = client.execute(req); } catch (ClientProtocolException e) { throw PersoniumCoreException.ServiceCollection.SC_INVALID_HTTP_RESPONSE_ERROR; } catch (Exception ioe) { throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe); } // ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode()); Header[] headersResEngine = objResponse.getAllHeaders(); // ? for (int i = 0; i < headersResEngine.length; i++) { // Engine????Transfer-Encoding???? // ?MW????????Content-Length???Transfer-Encoding???? // 2?????????????????????? if ("Transfer-Encoding".equalsIgnoreCase(headersResEngine[i].getName())) { continue; } // Engine????Date???? // Web??MW?Jetty???2????????? if (HttpHeaders.DATE.equalsIgnoreCase(headersResEngine[i].getName())) { continue; } res.header(headersResEngine[i].getName(), headersResEngine[i].getValue()); } InputStream isResBody = null; // ? HttpEntity entity = objResponse.getEntity(); if (entity != null) { try { isResBody = entity.getContent(); } catch (IllegalStateException e) { throw PersoniumCoreException.ServiceCollection.SC_UNKNOWN_ERROR.reason(e); } catch (IOException e) { throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(e); } final InputStream isInvariable = isResBody; // ?? StreamingOutput strOutput = new StreamingOutput() { @Override public void write(final OutputStream os) throws IOException { int chr; try { while ((chr = isInvariable.read()) != -1) { os.write(chr); } } finally { isInvariable.close(); } } }; res.entity(strOutput); } // ?? return res.build(); }