List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader
void setHeader(String str, String str2);
From source file:io.personium.client.http.RestAdapter.java
/** * This is the PUT method that receives the response body and uses Etag value and header map. * @param url Target Request URL// w ww . j a v a2s . c o m * @param data Data to be sent * @param etag ETag value * @param map HashMap of Request Header * @param contentType CONTENT-TYPE value * @return DcResponse object * @throws DaoException Exception thrown */ public PersoniumResponse put(String url, String data, String etag, HashMap<String, String> map, String contentType) throws DaoException { HttpUriRequest req = new PersoniumRequestBuilder().url(url).method(HttpMethods.PUT).contentType(contentType) .ifMatch(etag).body(data).token(getToken()).defaultHeaders(this.accessor.getDefaultHeaders()) .build(); for (Map.Entry<String, String> entry : map.entrySet()) { req.setHeader((String) entry.getKey(), (String) entry.getValue()); } return this.request(req); }
From source file:edu.isi.misd.tagfiler.client.JakartaClient.java
/** * Set the cookie for the request// w ww. j av a 2 s .co m * * @param cookie * the cookie to be set in the request * @param request * the request to be sent */ private void setCookie(String cookie, HttpUriRequest request) { if (cookie != null) { //httpclient.getCookieStore().clear(); request.setHeader("Cookie", cookieName + "=" + cookie); } }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java
/** * Executes the HTTP request./*ww w . j ava 2 s .c om*/ * <p/> * In case of any exception thrown by HttpClient, it will release the connection. In other cases it * is the duty of caller to do it, or process the input stream. * * @param repository to execute the HTTP method fpr * @param request resource store request that triggered the HTTP request * @param httpRequest HTTP request to be executed * @return response of making the request * @throws RemoteStorageException If an error occurred during execution of HTTP request */ private HttpResponse executeRequest(final ProxyRepository repository, final ResourceStoreRequest request, final HttpUriRequest httpRequest) throws RemoteStorageException { final URI methodUri = httpRequest.getURI(); if (getLogger().isDebugEnabled()) { getLogger().debug( "Invoking HTTP " + httpRequest.getMethod() + " method against remote location " + methodUri); } final RemoteStorageContext ctx = getRemoteStorageContext(repository); final HttpClient httpClient = HttpClientUtil.getHttpClient(CTX_KEY, ctx); httpRequest.setHeader("user-agent", formatUserAgentString(ctx, repository)); httpRequest.setHeader("accept", "*/*"); httpRequest.setHeader("accept-language", "en-us"); httpRequest.setHeader("accept-encoding", "gzip,deflate,identity"); httpRequest.setHeader("cache-control", "no-cache"); // HTTP keep alive should not be used, except when NTLM is used final Boolean isNtlmUsed = HttpClientUtil.isNTLMAuthenticationUsed(CTX_KEY, ctx); if (isNtlmUsed == null || !isNtlmUsed) { httpRequest.setHeader("Connection", "close"); httpRequest.setHeader("Proxy-Connection", "close"); } HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); final int statusCode = httpResponse.getStatusLine().getStatusCode(); final Header httpServerHeader = httpResponse.getFirstHeader("server"); checkForRemotePeerAmazonS3Storage(repository, httpServerHeader == null ? null : httpServerHeader.getValue()); Header proxyReturnedErrorHeader = httpResponse.getFirstHeader(NEXUS_MISSING_ARTIFACT_HEADER); boolean proxyReturnedError = proxyReturnedErrorHeader != null && Boolean.valueOf(proxyReturnedErrorHeader.getValue()); if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new RemoteAccessDeniedException(repository, methodUri.toASCIIString(), httpResponse.getStatusLine().getReasonPhrase()); } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new RemoteAuthenticationNeededException(repository, httpResponse.getStatusLine().getReasonPhrase()); } else if (statusCode == HttpStatus.SC_OK && proxyReturnedError) { throw new RemoteStorageException( "Invalid artifact found, most likely a proxy redirected to an HTML error page."); } return httpResponse; } catch (RemoteStorageException ex) { release(httpResponse); throw ex; } catch (ClientProtocolException ex) { release(httpResponse); throw new RemoteStorageException("Protocol error while executing " + httpRequest.getMethod() + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex); } catch (IOException ex) { release(httpResponse); throw new RemoteStorageException("Transport error while executing " + httpRequest.getMethod() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex); } }
From source file:edu.isi.misd.tagfiler.client.JakartaClient.java
/** * Execute a HttpUriRequest//from www . j a v a 2s . c o m * * @param request * the request to be executed * @param cookie * the cookie to be set in the request * @return the HTTP Response */ private ClientURLResponse execute(HttpUriRequest request, String cookie) { setCookie(cookie, request); request.setHeader("X-Machine-Generated", "true"); ClientURLResponse response = null; int count = 0; while (true) { try { response = new JakartaClientResponse(httpclient.execute(request)); break; } catch (ConnectException e) { // Can not connect and send the request // Retry maximum 10 times synchronized (this) { if (connectException == null || !connectException.equals(e.getMessage())) { System.err.println("ConnectException"); e.printStackTrace(); connectException = e.getMessage(); } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block synchronized (this) { if (clientProtocolException == null || !clientProtocolException.equals(e.getMessage())) { System.err.println("ClientProtocolException"); e.printStackTrace(); clientProtocolException = e.getMessage(); } } } catch (IOException e) { // The request was sent, but no response; connection might have been broken synchronized (this) { if (ioException == null || !ioException.equals(e.getMessage())) { System.err.println("IOException"); e.printStackTrace(); ioException = e.getMessage(); } } } if (++count > retries) { break; } else { // just in case if (response != null) { response.release(); } // sleep before retrying int delay = (int) Math.ceil((0.75 + Math.random() * 0.5) * Math.pow(10, count) * 0.00001); System.out.println("Retry delay: " + delay + " ms."); try { Thread.sleep(delay); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } return response; }
From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java
@Override protected Response sendXmlRequest(URL url, RequestMethod method, String xml) throws IOException, OAuthException { if (httpClient == null) throw new IOException("No HTTP client was specified!"); if (method == null) method = RequestMethod.GET;/*from w w w.ja va 2s . c o m*/ xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml) : null; HttpUriRequest request = null; if (RequestMethod.GET.equals(method)) { request = new HttpGet(url.toString()); } else if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else if (RequestMethod.DELETE.equals(method)) { request = new HttpDelete(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } if (xml != null && request instanceof HttpEntityEnclosingRequest) { ContentType xmlType = ContentType.create("application/xml", getEncoding()); request.setHeader("Content-Type", xmlType.toString()); request.setHeader("Content-Language", "en-US"); StringEntity xmlEntity = new StringEntity(xml, xmlType); ((HttpEntityEnclosingRequest) request).setEntity(xmlEntity); } request.setHeader("Accept", "application/xml"); // sign request getAuthConsumer().sign(request); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleAPITalker.java
/** * Returns an object if all went well. Returns null if no upload was done. * Will set only remote id, etag, position and parent fields. * /*from w w w .jav a2 s.c o m*/ * Updates the task in place and also returns it. * * @throws PreconditionException * @throws JSONException */ public GoogleTask uploadTask(final GoogleTask task, final GoogleTaskList pList) throws IOException, PreconditionException, JSONException { if (pList.remoteId == null || pList.remoteId.isEmpty()) { Log.d(TAG, "Invalid list ID found for uploadTask"); return null; // Invalid list id } // If we are trying to upload a deleted task which does not exist on // server, we can ignore it. might happen with conflicts if (task.isDeleted() && (task.remoteId == null || task.remoteId.isEmpty())) { Log.d(TAG, "Trying to upload a deleted non-synced note, ignoring: " + task.title); return null; } HttpUriRequest httppost; if (task.remoteId != null && !task.remoteId.isEmpty()) { if (task.isDeleted()) { httppost = new HttpPost(TaskURL(task.remoteId, pList.remoteId)); httppost.setHeader("X-HTTP-Method-Override", "DELETE"); } else { httppost = new HttpPost(TaskURL_ETAG_ID_UPDATED(task.remoteId, pList.remoteId)); // apache does not include PATCH requests, but we can force a // post to be a PATCH request httppost.setHeader("X-HTTP-Method-Override", "PATCH"); } // Always set ETAGS for tasks // setHeaderStrongEtag(httppost, task.etag); } else { if (task.isDeleted()) { return task; // Don't sync deleted items which do not exist on // the server } //Log.d(TAG, "ID IS NULL: " + task.title); httppost = new HttpPost(AllTasksInsert(pList.remoteId)); // task.didRemoteInsert = true; // Need this later } setAuthHeader(httppost); AndroidHttpClient.modifyRequestToAcceptGzipResponse(httppost); // Log.d(TAG, httppost.getRequestLine().toString()); // for (Header header : httppost.getAllHeaders()) { // Log.d(TAG, header.getName() + ": " + header.getValue()); // } if (!task.isDeleted()) { setPostBody(httppost, task); } String stringResponse = parseResponse(client.execute(httppost)); // If we deleted the note, we will get an empty response. Return the // same element back. if (task.isDeleted()) { Log.d(TAG, "deleted and Stringresponse: " + stringResponse); } else { JSONObject jsonResponse = new JSONObject(stringResponse); // Log.d(TAG, jsonResponse.toString()); // Will return a task, containing id and etag. always update // fields task.remoteId = jsonResponse.getString(GoogleTask.ID); // task.etag = jsonResponse.getString("etag"); if (jsonResponse.has(GoogleTask.UPDATED)) { try { task.updated = RFC3339Date.parseRFC3339Date(jsonResponse.getString(GoogleTask.UPDATED)) .getTime(); } catch (Exception e) { task.updated = 0L; } } } return task; }
From source file:io.personium.jersey.engine.test.ScriptTest.java
/** * ???Service?./*from w w w . java 2s .c o m*/ */ @Test public final void serviceNotFound() { if (isServiceTest) { String url = String.format("%s/%s/%s/%s/test?cell=%s", baseUrl, cellName, boxName, "notfoundsvccol", cellName); try { HttpUriRequest req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build(); req.setHeader(KEY_HEADER_BASEURL, baseUrl); String version = getVersion(); if (version != null && !(version.equals(""))) { req.setHeader("X-Personium-Version", version); } request(req); fail(); } catch (DaoException e) { assertEquals("404", e.getCode()); } } }
From source file:com.example.fertilizercrm.common.httpclient.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 *///from ww w .j a va 2 s . co m protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.setHeader("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)); } return new RequestHandle(request); }
From source file:com.hypers.frame.http.core.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 *///from ww w .j ava 2 s . co m protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.setHeader("Content-Type", contentType); } // //token // uriRequest.addHeader("token", UserDataManger.getToken(context)); 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:com.aoeng.degu.utils.net.asyncthhpclient.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 *///w w w . j av a2 s. co m protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.setHeader("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); }