List of usage examples for org.apache.http.client.methods HttpUriRequest getParams
@Deprecated HttpParams getParams();
From source file:com.sun.jersey.client.apache4.ApacheHttpClient4Handler.java
private HttpUriRequest getUriHttpRequest(final ClientRequest cr) { final String strMethod = cr.getMethod(); final URI uri = cr.getURI(); final Boolean bufferingEnabled = isBufferingEnabled(cr); final HttpEntity entity = getHttpEntity(cr, bufferingEnabled); final HttpUriRequest request; if (strMethod.equals("GET")) { request = new HttpGet(uri); } else if (strMethod.equals("POST")) { request = new HttpPost(uri); } else if (strMethod.equals("PUT")) { request = new HttpPut(uri); } else if (strMethod.equals("DELETE")) { request = new HttpDelete(uri); } else if (strMethod.equals("HEAD")) { request = new HttpHead(uri); } else if (strMethod.equals("OPTIONS")) { request = new HttpOptions(uri); } else {/* w ww. j a v a 2 s .c om*/ request = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return strMethod; } @Override public URI getURI() { return uri; } }; } if (entity != null && request instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) request).setEntity(entity); } else if (entity != null) { throw new ClientHandlerException( "Adding entity to http method " + cr.getMethod() + " is not supported."); } // Set the read timeout final Integer readTimeout = (Integer) cr.getProperties().get(ApacheHttpClient4Config.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { request.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, readTimeout); } // Set chunk size final Integer chunkSize = (Integer) cr.getProperties().get(ClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); if (chunkSize != null && !bufferingEnabled) { client.getParams().setIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, chunkSize); } return request; }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }// w w w . ja v a2s .com if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && ((headers == null) || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) { hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); // CookieStore cookieStore = new BasicCookieStore(); // context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { //response = client.execute(hr, context); response = execute(hr, client, context); getCookie(client); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); //response = client.execute(hr, context); response = execute(hr, client, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if ((code < 200) || (code >= 300)) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } is = entity.getContent(); if ("gzip".equalsIgnoreCase(getEncoding(entity))) { is = new GZIPInputStream(is); } copy(is, os, (int) entity.getContentLength()); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || (file.length() == 0)) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:org.codegist.crest.HttpClientRestService.java
private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException { HttpUriRequest uriRequest; String queryString = ""; if (request.getQueryParams() != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }// w w w. j a va2 s . c om String qs = URLEncodedUtils.format(params, request.getEncoding()); queryString = Strings.isNotBlank(qs) ? ("?" + qs) : ""; } String uri = request.getUri().toString() + queryString; switch (request.getMeth()) { default: case GET: uriRequest = new HttpGet(uri); break; case POST: uriRequest = new HttpPost(uri); break; case PUT: uriRequest = new HttpPut(uri); break; case DELETE: uriRequest = new HttpDelete(uri); break; case HEAD: uriRequest = new HttpHead(uri); break; } if (uriRequest instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest); HttpEntity entity; if (Params.isForUpload(request.getBodyParams().values())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { ContentBody body; if (param.getValue() instanceof InputStream) { body = new InputStreamBody((InputStream) param.getValue(), param.getKey()); } else if (param.getValue() instanceof File) { body = new FileBody((File) param.getValue()); } else if (param.getValue() != null) { body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset()); } else { body = new StringBody(null); } multipartEntity.addPart(param.getKey(), body); } entity = multipartEntity; } else { List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size()); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue() != null ? param.getValue().toString() : null)); } entity = new UrlEncodedFormEntity(params, request.getEncoding()); } enclosingRequestBase.setEntity(entity); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { uriRequest.setHeader(header.getKey(), header.getValue()); } } if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) { HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(), request.getConnectionTimeout().intValue()); } if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) { HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue()); } return uriRequest; }
From source file:com.tandong.sa.aq.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }/* www . j av a2 s . c om*/ if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT); hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = client.execute(hr, context); byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); Header[] hs = response.getAllHeaders(); HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length); for (Header h : hs) { responseHeaders.put(h.getName(), h.getValue()); } setResponseHeaders(responseHeaders); File file = null; if (code < 200 || code >= 300) { try { if (entity != null) { InputStream is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } //AQUtility.time("copy"); copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength()); //AQUtility.timeEnd("copy", 0); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:com.androidquery.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }/*w ww .ja v a 2 s . c om*/ if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { response = client.execute(hr, context); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); response = client.execute(hr, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if (code < 200 || code >= 300) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } //AQUtility.time("copy"); copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength()); //AQUtility.timeEnd("copy", 0); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }//from w w w . j a v a 2 s . com if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { //response = client.execute(hr, context); response = execute(hr, client, context); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); //response = client.execute(hr, context); response = execute(hr, client, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if (code < 200 || code >= 300) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } is = entity.getContent(); if ("gzip".equalsIgnoreCase(getEncoding(entity))) { is = new GZIPInputStream(is); } copy(is, os, (int) entity.getContentLength()); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java
public HttpResponse fetch(org.apache.shindig.gadgets.http.HttpRequest request) throws GadgetException { HttpUriRequest httpMethod = null;// w w w . j a va 2 s. c o m Preconditions.checkNotNull(request); final String methodType = request.getMethod(); final org.apache.http.HttpResponse response; final long started = System.currentTimeMillis(); // Break the request Uri to its components: Uri uri = request.getUri(); if (StringUtils.isEmpty(uri.getAuthority())) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Missing domain name for request: " + uri, HttpServletResponse.SC_BAD_REQUEST); } if (StringUtils.isEmpty(uri.getScheme())) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Missing schema for request: " + uri, HttpServletResponse.SC_BAD_REQUEST); } String[] hostparts = StringUtils.splitPreserveAllTokens(uri.getAuthority(), ':'); int port = -1; // default port if (hostparts.length > 2) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Bad host name in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST); } if (hostparts.length == 2) { try { port = Integer.parseInt(hostparts[1]); } catch (NumberFormatException e) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Bad port number in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST); } } String requestUri = uri.getPath(); // Treat path as / if set as null. if (uri.getPath() == null) { requestUri = "/"; } if (uri.getQuery() != null) { requestUri += '?' + uri.getQuery(); } // Get the http host to connect to. HttpHost host = new HttpHost(hostparts[0], port, uri.getScheme()); try { if ("POST".equals(methodType) || "PUT".equals(methodType)) { HttpEntityEnclosingRequestBase enclosingMethod = ("POST".equals(methodType)) ? new HttpPost(requestUri) : new HttpPut(requestUri); if (request.getPostBodyLength() > 0) { enclosingMethod .setEntity(new InputStreamEntity(request.getPostBody(), request.getPostBodyLength())); } httpMethod = enclosingMethod; } else if ("GET".equals(methodType)) { httpMethod = new HttpGet(requestUri); } else if ("HEAD".equals(methodType)) { httpMethod = new HttpHead(requestUri); } else if ("DELETE".equals(methodType)) { httpMethod = new HttpDelete(requestUri); } for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) { httpMethod.addHeader(entry.getKey(), StringUtils.join(entry.getValue(), ',')); } // Disable following redirects. if (!request.getFollowRedirects()) { httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); } // HttpClient doesn't handle all cases when breaking url (specifically '_' in domain) // So lets pass it the url parsed: response = FETCHER.execute(host, httpMethod); if (response == null) { throw new IOException("Unknown problem with request"); } long now = System.currentTimeMillis(); if (now - started > slowResponseWarning) { slowResponseWarning(request, started, now); } return makeResponse(response); } catch (Exception e) { long now = System.currentTimeMillis(); // Find timeout exceptions, respond accordingly if (TIMEOUT_EXCEPTIONS.contains(e.getClass())) { LOG.info("Timeout for " + request.getUri() + " Exception: " + e.getClass().getName() + " - " + e.getMessage() + " - " + (now - started) + "ms"); return HttpResponse.timeout(); } LOG.log(Level.INFO, "Got Exception fetching " + request.getUri() + " - " + (now - started) + "ms", e); // Separate shindig error from external error throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // cleanup any outstanding resources.. if (httpMethod != null) try { httpMethod.abort(); } catch (UnsupportedOperationException e) { // ignore } } }