List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(String str, String str2);
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java
protected void setHeaders(HttpUriRequest method) { HttpMethodConfiguration config = httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); if (config == null || config.isUseDefaultHeaders()) { // TODO: merge with the other headers and have some better defaults, unify with lightweight headers method.addHeader("Cache-control", "no-cache"); method.addHeader("Cache-store", "no-store"); method.addHeader("Pragma", "no-cache"); method.addHeader("Expires", "0"); method.addHeader("Accept-Encoding", "gzip"); }/*w ww . j av a2 s . co m*/ if (httpHeaders != null) { for (Map.Entry<Object, Object> entry : httpHeaders.entrySet()) { method.setHeader((String) entry.getKey(), (String) entry.getValue()); } } Header[] headers = config == null ? null : config.asRequestHeaders(); if (headers != null) { for (Header header : headers) { method.setHeader(header); } } }
From source file:com.mobilesolutionworks.android.http.WorksHttpClient.java
/** * Execute the request on this works http client. * * @param context application context//from ww w . ja v a 2s . c om * @param request works http request * @param listener works operation listener * @return works http response */ public static <Result> WorksHttpResponse<Result> executeOperation(Context context, WorksHttpRequest request, final WorksHttpOperationListener listener) { final HttpUriRequest httpRequest; HttpResponse httpResponse = null; WorksHttpResponse<Result> response = new WorksHttpResponse<Result>(); response.request = request; WorksHttpClient instance = WorksHttpClient.getInstance(context); AndroidHttpClient client = instance.getHttpClient(); switch (request.method) { default: case GET: { Uri.Builder builder = Uri.parse(request.url).buildUpon(); if (request.httpParams != null) { for (Map.Entry<String, String> entry : request.httpParams.entrySet()) { builder.appendQueryParameter(entry.getKey(), entry.getValue()); } } httpRequest = new HttpGet(builder.build().toString()); break; } case POST: { HttpPost httpPost = new HttpPost(request.url); if (request.httpParams != null) { List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, String> entry : request.httpParams.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity result; try { result = new UrlEncodedFormEntity(params, "UTF-8"); httpPost.setEntity(result); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } httpRequest = httpPost; } } request.abortable = new WorksHttpRequest.Abortable() { @Override public void abort() { httpRequest.abort(); } }; if (request.preExecutor != null) { request.preExecutor.onPreExecute(request, httpRequest); } listener.onPreExecute(request, httpRequest); httpRequest.addHeader("Works-Http-Client", instance.getName()); try { HttpContext httpContext = listener.getHttpContext(); httpResponse = client.execute(httpRequest, httpContext); if (listener.onValidateResponse(request, httpResponse)) { response.statusCode = httpResponse.getStatusLine().getStatusCode(); boolean handled = false; try { handled = listener.onHandleResponse(request, httpRequest, response, httpResponse); } catch (Exception e) { response.markErrorInHandler(e); handled = true; } if (!handled) { int contentLength = -1; Header[] headers = httpResponse.getHeaders("Content-Length"); if (headers != null) { for (Header header : headers) { String value = header.getValue(); contentLength = TypeUtils.parseInt(value); } } if (request.returnTransfer) { InputStream content = httpResponse.getEntity().getContent(); response.text = IOUtils .consumeAsString(new CountingInputStream(content, listener, contentLength)); } else if (request.out != null) { InputStream content = httpResponse.getEntity().getContent(); IOUtils.copy(new CountingInputStream(content, listener, contentLength), request.out); } response.markSuccess(); } } else { response.markInvalidHttpStatus(httpResponse.getStatusLine().getStatusCode()); } } catch (Exception e) { response.markErrorInExecution(e); } finally { try { client.close(); } catch (Exception e) { // e.printStackTrace(); } if (httpResponse != null) { try { httpResponse.getEntity().consumeContent(); } catch (IOException e) { // e.printStackTrace(); } } } return response; }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, CacheParams cacheParams, AsyncHttpResponseHandler responseHandler, Context context) {// w ww .j a va2 s . c om if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool.submit( new AsyncHttpRequest(client, httpContext, uriRequest, cacheParams, responseHandler, context)); 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.vk.sdk.api.httpClient.VKHttpClient.java
/** * Prepares new "normal" request from VKRequest * * @param vkRequest Request, created for some method * @return Prepared request for creating VKHttpOperation *//*from w ww . j ava 2 s .co m*/ public static HttpUriRequest requestWithVkRequest(VKRequest vkRequest) { HttpUriRequest request = null; VKParameters preparedParameters = vkRequest.getPreparedParameters(); StringBuilder urlStringBuilder = new StringBuilder(String.format(Locale.US, "http%s://api.vk.com/method/%s", vkRequest.secure ? "s" : "", vkRequest.methodName)); switch (vkRequest.httpMethod) { case GET: if (preparedParameters.size() > 0) { urlStringBuilder.append("?").append(VKStringJoiner.joinUriParams(preparedParameters)); } request = new HttpGet(urlStringBuilder.toString()); break; case POST: HttpPost post = new HttpPost(urlStringBuilder.toString()); ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(preparedParameters.size()); for (Map.Entry<String, Object> entry : preparedParameters.entrySet()) { Object value = entry.getValue(); if (value instanceof VKAttachments) { pairs.add( new BasicNameValuePair(entry.getKey(), ((VKAttachments) value).toAttachmentsString())); } else if (value instanceof Collection) { Collection<?> values = (Collection<?>) value; for (Object v : values) { // This will add a parameter for each value in the Collection/List pairs.add(new BasicNameValuePair(String.format("%s[]", entry.getKey()), v == null ? null : String.valueOf(v))); } } else { pairs.add(new BasicNameValuePair(entry.getKey(), value == null ? null : String.valueOf(value))); } } try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8"); post.setEntity(entity); } catch (UnsupportedEncodingException e) { return null; } request = post; break; } Map<String, String> defaultHeaders = getDefaultHeaders(); for (String key : defaultHeaders.keySet()) { request.addHeader(key, defaultHeaders.get(key)); } return request; }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java
protected void setHeaders(HttpUriRequest method) { HttpMethodConfiguration config = httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); if (config == null || config.isUseDefaultHeaders()) { // TODO: merge with the other headers and have some better defaults, unify with lightweight headers method.addHeader("Cache-control", "no-cache"); method.addHeader("Cache-store", "no-store"); method.addHeader("Pragma", "no-cache"); method.addHeader("Expires", "0"); method.addHeader("Accept-Encoding", "gzip"); method.addHeader("User-Agent", DEFAULT_USER_AGENT); }/*from www. j av a 2 s .c om*/ if (httpHeaders != null) { for (Map.Entry<Object, Object> entry : httpHeaders.entrySet()) { method.addHeader((String) entry.getKey(), (String) entry.getValue()); } } Header[] headers = config == null ? null : config.asRequestHeaders(); if (headers != null) { for (Header header : headers) { method.addHeader(header); } } }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
/** * ???/* w w w .j a va 2 s. c o m*/ * * @param client * @param httpContext * @param uriRequest * @param contentType * @param cacheParams * @param responseHandler * @param context * @param isGetDataBase */ protected void sendRequestByDateBase(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, CacheParams cacheParams, AsyncHttpResponseHandler responseHandler, Context context, boolean isGetDataBase) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, cacheParams, responseHandler, context, isGetDataBase)); 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)); } }
From source file:org.openrdf.http.client.SparqlSession.java
private HttpResponse sendGraphQueryViaHttp(HttpUriRequest method, boolean requireContext, Set<RDFFormat> rdfFormats) throws RepositoryException, IOException, QueryInterruptedException, MalformedQueryException { List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, requireContext, getPreferredRDFFormat()); for (String acceptParam : acceptParams) { method.addHeader(ACCEPT_PARAM_NAME, acceptParam); }//from w w w . j av a2s. c o m try { return executeOK(method); } catch (RepositoryException e) { throw e; } catch (MalformedQueryException e) { throw e; } catch (QueryInterruptedException e) { throw e; } catch (OpenRDFException e) { throw new RepositoryException(e); } }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
/** * post//from w w w.j a v a 2 s . c o m * * @param client * @param httpContext * @param uriRequest * @param contentType * @param cacheParams * @param responseHandler * @param context * @param requestParam */ protected void sendRequestPost(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, CacheParams cacheParams, AsyncHttpResponseHandler responseHandler, Context context, String requestParam) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, cacheParams, responseHandler, context, requestParam)); 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:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
private HttpResponse sendGraphQueryViaHttp(HttpUriRequest method, boolean requireContext, Set<RDFFormat> rdfFormats) throws RepositoryException, IOException, QueryInterruptedException, MalformedQueryException { List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, requireContext, getPreferredRDFFormat()); method.addHeader(ACCEPT_PARAM_NAME, commaJoiner.join(acceptParams)); try {//w w w. j a v a 2 s. c o m return executeOK(method); } catch (RepositoryException | MalformedQueryException | QueryInterruptedException e) { throw e; } catch (RDF4JException e) { throw new RepositoryException(e); } }
From source file:edu.ucsb.nceas.ezid.EZIDService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * @return byte[] containing the response body *///ww w . jav a 2 s . c o m private byte[] sendRequest(int requestType, String uri, String requestBody) throws EZIDException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EZIDException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpclient.execute(request, handler); } catch (ClientProtocolException e) { throw new EZIDException(e.getMessage()); } catch (IOException e) { throw new EZIDException(e.getMessage()); } return body; }