List of usage examples for org.apache.commons.httpclient.params HttpMethodParams setParameter
public void setParameter(String paramString, Object paramObject)
From source file:com.ibm.stocator.fs.swift.SwiftAPIDirect.java
/** * GET object/* w w w . j a v a 2 s . com*/ * * @param path path to object * @param authToken authentication token * @param bytesFrom from from * @param bytesTo bytes to * @return SwiftGETResponse that includes input stream and length * @throws IOException if network errors */ public static SwiftGETResponse getObject(Path path, String authToken, long bytesFrom, long bytesTo) throws IOException { GetMethod method = new GetMethod(path.toString()); method.addRequestHeader(new Header("X-Auth-Token", authToken)); if (bytesTo > 0) { final String rangeValue = String.format("bytes=%d-%d", bytesFrom, bytesTo); method.addRequestHeader(new Header(Constants.RANGES_HTTP_HEADER, rangeValue)); } HttpMethodParams methodParams = method.getParams(); methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 15000); methodParams.setSoTimeout(60000); method.addRequestHeader(Constants.USER_AGENT_HTTP_HEADER, Constants.STOCATOR_USER_AGENT); final HttpClient client = new HttpClient(); int statusCode = client.executeMethod(method); SwiftInputStreamWrapper httpStream = new SwiftInputStreamWrapper(method); SwiftGETResponse getResponse = new SwiftGETResponse(httpStream, method.getResponseContentLength()); return getResponse; }
From source file:apm.common.utils.HttpTookit.java
/** * HTTP POST?HTML/*from w w w. ja v a 2 s.co m*/ * * @param url * URL? * @param params * ?,?null * @param charset * * @param pretty * ? * @return ?HTML */ public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new PostMethod(url); // Http Post? if (params != null) { HttpMethodParams p = new HttpMethodParams(); for (Map.Entry<String, String> entry : params.entrySet()) { p.setParameter(entry.getKey(), entry.getValue()); } method.setParams(p); } try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) { response.append(line).append(System.getProperty("line.separator")); } else { response.append(line); } } reader.close(); } } catch (IOException e) { log.error("HTTP Post" + url + "??", e); } finally { method.releaseConnection(); } return response.toString(); }
From source file:net.cbtltd.server.WebService.java
/** * Gets the HTTP response./*from ww w .j av a2s . co m*/ * * @param url the url of the service. * @param nameids the parameter key value pairs. * @return the HTTP response string. * @throws Throwable the exception that can be thrown. */ public static final String getHttpResponse(String url, NameId[] nameids) throws Throwable { GetMethod get = new GetMethod(url); get.addRequestHeader("Accept", "text/plain"); HttpMethodParams params = new HttpMethodParams(); get.setParams(params); for (NameId nameid : nameids) { params.setParameter(nameid.getId(), nameid.getName()); } HttpClient httpclient = new HttpClient(); int rs = httpclient.executeMethod(get); LOG.debug("rs=" + rs + " " + get.getResponseBodyAsString()); return get.getResponseBodyAsString(); }
From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java
/** * Gets the http method./* w w w. j a va 2s.c om*/ * * @param httpClientConfig * the http client config * @return the http method * @throws HttpClientException * the http client util exception */ private static HttpMethod getHttpMethod(HttpClientConfig httpClientConfig) throws HttpClientException { if (log.isDebugEnabled()) { log.debug("[httpClientConfig]:{}", JsonUtil.format(httpClientConfig)); } HttpMethod httpMethod = setUriAndParams(httpClientConfig); HttpMethodParams httpMethodParams = httpMethod.getParams(); // TODO httpMethodParams.setParameter(HttpMethodParams.USER_AGENT, DEFAULT_USER_AGENT); // ???? httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); return httpMethod; }
From source file:com.zimbra.cs.service.FeedManager.java
private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd) throws ServiceException, HttpException, IOException { assert !Strings.isNullOrEmpty(url); HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); // cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr. // see comments in ZimbraHttpConnectionManager // client.setConnectionTimeout(10000); HttpMethodParams params = new HttpMethodParams(); params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, MimeConstants.P_CHARSET_UTF8); params.setSoTimeout(60000);// w w w. ja va2s.c o m GetMethod get = null; BufferedInputStream content = null; long lastModified = 0; String expectedCharset = MimeConstants.P_CHARSET_UTF8; int redirects = 0; int statusCode = HttpServletResponse.SC_NOT_FOUND; try { do { String lcurl = url.toLowerCase(); if (lcurl.startsWith("webcal:")) { url = "http:" + url.substring(7); } else if (lcurl.startsWith("feed:")) { url = "http:" + url.substring(5); } else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) { throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null); } // username and password are encoded in the URL as http://user:pass@host/... if (url.indexOf('@') != -1) { HttpURL httpurl = lcurl.startsWith("https:") ? new HttpsURL(url) : new HttpURL(url); if (httpurl.getUser() != null) { String user = httpurl.getUser(); if (user.indexOf('%') != -1) { try { user = URLDecoder.decode(user, "UTF-8"); } catch (OutOfMemoryError e) { Zimbra.halt("out of memory", e); } catch (Throwable t) { } } UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, httpurl.getPassword()); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, creds); } } try { get = new GetMethod(url); } catch (OutOfMemoryError e) { Zimbra.halt("out of memory", e); return null; } catch (Throwable t) { throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, t); } get.setParams(params); get.setFollowRedirects(true); get.setDoAuthentication(true); get.addRequestHeader("User-Agent", HTTP_USER_AGENT); get.addRequestHeader("Accept", HTTP_ACCEPT); if (fsd != null && fsd.getLastSyncDate() > 0) { String lastSyncAt = org.apache.commons.httpclient.util.DateUtil .formatDate(new Date(fsd.getLastSyncDate())); get.addRequestHeader("If-Modified-Since", lastSyncAt); } HttpClientUtil.executeMethod(client, get); Header locationHeader = get.getResponseHeader("location"); if (locationHeader != null) { // update our target URL and loop again to do another HTTP GET url = locationHeader.getValue(); get.releaseConnection(); } else { statusCode = get.getStatusCode(); if (statusCode == HttpServletResponse.SC_OK) { Header contentEncoding = get.getResponseHeader("Content-Encoding"); InputStream respInputStream = get.getResponseBodyAsStream(); if (contentEncoding != null) { if (contentEncoding.getValue().indexOf("gzip") != -1) { respInputStream = new GZIPInputStream(respInputStream); } } content = new BufferedInputStream(respInputStream); expectedCharset = get.getResponseCharSet(); Header lastModHdr = get.getResponseHeader("Last-Modified"); if (lastModHdr == null) { lastModHdr = get.getResponseHeader("Date"); } if (lastModHdr != null) { try { Date d = org.apache.commons.httpclient.util.DateUtil .parseDate(lastModHdr.getValue()); lastModified = d.getTime(); } catch (DateParseException e) { ZimbraLog.misc.warn( "unable to parse Last-Modified/Date header: " + lastModHdr.getValue(), e); lastModified = System.currentTimeMillis(); } } else { lastModified = System.currentTimeMillis(); } } else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync"); return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified); } else { throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusLine().toString(), null); } break; } } while (++redirects <= MAX_REDIRECTS); } catch (ServiceException ex) { if (get != null) { get.releaseConnection(); } throw ex; } catch (HttpException ex) { if (get != null) { get.releaseConnection(); } throw ex; } catch (IOException ex) { if (get != null) { get.releaseConnection(); } throw ex; } RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified); rdi.setGetMethod(get); return rdi; }
From source file:edu.du.penrose.systems.fedoraApp.tests.sendEctdRestResults.java
public void testRun() { try {/*from w ww . j a v a2 s . c o m*/ HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "fedoraProxy Client"); final String HOST = "130.253.33.105"; final String PORT = "8085"; final String CMD = "/library/updatePid"; final String KEY = "6b476c7e50726949347162353c7e3d7271336e6f3e3e4c2d703d762d24"; String objid = "du_174_1793_primary_1999_kelly"; String pid = "178"; StringBuffer ectdResultsUrl = new StringBuffer("http://"); ectdResultsUrl.append(HOST); ectdResultsUrl.append(":"); ectdResultsUrl.append(PORT); ectdResultsUrl.append(CMD); GetMethod method = new GetMethod(ectdResultsUrl.toString()); HttpMethodParams params = new HttpClientParams(); params.setParameter("id", objid); params.setParameter("pid", pid); method.setParams(params); try { int returnCode = client.executeMethod(method); if (returnCode != HttpStatus.SC_OK) { System.err.println("ERROR"); } } catch (Exception e) { System.err.println(e); } finally { method.releaseConnection(); } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } }
From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java
/**download methods*/ @Override/*from w w w . j a va 2 s. c o m*/ protected byte[] downloadFile() { this.setRunning(true); byte[] result = null; InputStream is = null; ByteArrayOutputStream bas = null; String url = this.getURL(); PLFileDownloaderListener listener = this.getListener(); boolean hasListener = (listener != null); int responseCode = -1; long startTime = System.currentTimeMillis(); // HttpClient instance HttpClient client = new HttpClient(); // Method instance HttpMethod method = new GetMethod(url); // Method parameters HttpMethodParams methodParams = method.getParams(); methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android"); methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false)); try { // Execute the method responseCode = client.executeMethod(method); if (responseCode != HttpStatus.SC_OK) throw new IOException(method.getStatusText()); // Get content length Header header = method.getRequestHeader("Content-Length"); long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1); if (this.isRunning()) { if (hasListener) listener.didBeginDownload(url, startTime); } else throw new PLRequestInvalidatedException(url); // Get response body as stream is = method.getResponseBodyAsStream(); bas = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int length = 0, total = 0; // Read stream while ((length = is.read(buffer)) != -1) { if (this.isRunning()) { bas.write(buffer, 0, length); total += length; if (hasListener) listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f)); } else throw new PLRequestInvalidatedException(url); } if (total == 0) throw new IOException("Request data has invalid size (0)"); // Get data if (this.isRunning()) { result = bas.toByteArray(); if (hasListener) listener.didEndDownload(url, result, System.currentTimeMillis() - startTime); } else throw new PLRequestInvalidatedException(url); } catch (Throwable e) { if (this.isRunning()) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); if (hasListener) listener.didErrorDownload(url, e.toString(), responseCode, result); } } finally { if (bas != null) { try { bas.close(); } catch (IOException e) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); } } if (is != null) { try { is.close(); } catch (IOException e) { PLLog.error("PLHTTPFileDownloader::downloadFile", e); } } // Release the connection method.releaseConnection(); } this.setRunning(false); return result; }
From source file:com.worldline.easycukes.rest.client.RestService.java
/** * Allows to send a PUT request, with parameters using JSON format * * @param path path to be used for the PUT request * @param data paremeters to be used (JSON format) as a string *//* ww w . j a v a 2 s .c o m*/ @SuppressWarnings("unchecked") public void sendPut(final String path, final String data) { String fullpath = path; if (path.startsWith("/")) fullpath = baseUrl + path; log.info("Sending PUT request to " + fullpath); final PutMethod method = new PutMethod(fullpath); for (final Map.Entry<String, String> header : requestHeaders.entrySet()) method.setRequestHeader(header.getKey(), header.getValue()); if (data != null) { JSONObject jsonObject = null; try { jsonObject = JSONHelper.toJSONObject(data); for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) { final String param = iterator.next(); HttpMethodParams methodParams = new HttpMethodParams(); methodParams.setParameter(param, (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null); method.setParams(methodParams); } } catch (final ParseException e) { log.error("Sorry, parameters are not proper JSON...", e); } } try { if (nonProxyHost != null && fullpath.contains(nonProxyHost)) { httpClient.getHostConfiguration().setProxyHost(null); } final int statusCode = httpClient.executeMethod(method); response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(), statusCode); } catch (final IOException e) { log.error(e.getMessage(), e); } finally { method.releaseConnection(); } }
From source file:com.worldline.easycukes.rest.client.RestService.java
/** * Allows to send a DELETE request, with parameters using JSON format * * @param path path to be used for the DELETE request * @param data paremeters to be used (JSON format) as a string *///from ww w .j a va 2s. c om @SuppressWarnings("unchecked") public void sendDelete(final String path, final String data) { String fullpath = path; if (path.startsWith("/")) fullpath = baseUrl + path; log.info("Sending DELETE request to " + fullpath); final DeleteMethod method = new DeleteMethod(fullpath); for (final Map.Entry<String, String> header : requestHeaders.entrySet()) method.setRequestHeader(header.getKey(), header.getValue()); if (data != null) { JSONObject jsonObject = null; try { jsonObject = JSONHelper.toJSONObject(data); for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) { final String param = iterator.next(); HttpMethodParams methodParams = new HttpMethodParams(); methodParams.setParameter(param, (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null); method.setParams(methodParams); } } catch (final ParseException e) { log.error("Sorry, parameters are not proper JSON...", e); } } try { if (nonProxyHost != null && fullpath.contains(nonProxyHost)) { httpClient.getHostConfiguration().setProxyHost(null); } final int statusCode = httpClient.executeMethod(method); response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(), statusCode); } catch (final IOException e) { log.error(e.getMessage(), e); } finally { method.releaseConnection(); } }
From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java
@Override public void executeMethod(final HttpMethod method, final ClientRequest cr) { final Map<String, Object> props = cr.getProperties(); method.setDoAuthentication(true);/*from w w w . j a v a 2 s. c om*/ final HttpMethodParams methodParams = method.getParams(); // Set the handle cookies property if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) { methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } // Set the interactive and credential provider properties if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) { CredentialsProvider provider = (CredentialsProvider) props .get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER); if (provider == null) { provider = DEFAULT_CREDENTIALS_PROVIDER; } methodParams.setParameter(CredentialsProvider.PROVIDER, provider); } else { methodParams.setParameter(CredentialsProvider.PROVIDER, null); } // Set the read timeout final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { methodParams.setSoTimeout(readTimeout); } if (method instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method; if (cr.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(cr); final Integer chunkedEncodingSize = (Integer) props .get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); if (chunkedEncodingSize != null) { // There doesn't seems to be a way to set the chunk size. entMethod.setContentChunked(true); // It is not possible for a MessageBodyWriter to modify // the set of headers before writing out any bytes to // the OutputStream // This makes it impossible to use the multipart // writer that modifies the content type to add a boundary // parameter writeOutBoundHeaders(cr.getHeaders(), method); // Do not buffer the request entity when chunked encoding is // set entMethod.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream out) throws IOException { re.writeRequestEntity(out); } @Override public long getContentLength() { return re.getSize(); } @Override public String getContentType() { return re.getMediaType().toString(); } }); } else { entMethod.setContentChunked(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity(new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(cr.getMetadata(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); entMethod.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return true; } @Override public void writeRequest(OutputStream out) throws IOException { out.write(content); } @Override public long getContentLength() { return content.length; } @Override public String getContentType() { return re.getMediaType().toString(); } }); } } else { writeOutBoundHeaders(cr.getHeaders(), method); } } else { writeOutBoundHeaders(cr.getHeaders(), method); // Follow redirects method.setFollowRedirects(cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS)); } try { httpClient.executeMethod(getHostConfiguration(httpClient, props), method, getHttpState(props)); } catch (Exception e) { method.releaseConnection(); throw new ClientHandlerException(e); } }