List of usage examples for org.apache.commons.httpclient.methods EntityEnclosingMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.basho.riak.client.RiakObject.java
/** * Serializes this object to an existing {@link HttpMethod} which can be * sent as an HTTP request. Specifically, sends the object's link, * user-defined metadata and vclock as HTTP headers and the value as the * body. Used by {@link RiakClient} to create PUT requests. *///from w w w . j ava2s . co m public void writeToHttpMethod(HttpMethod httpMethod) { // Serialize headers String basePath = getBasePathFromHttpMethod(httpMethod); writeLinks(httpMethod, basePath); for (String name : userMetaData.keySet()) { httpMethod.setRequestHeader(Constants.HDR_USERMETA_REQ_PREFIX + name, userMetaData.get(name)); } if (vclock != null) { httpMethod.setRequestHeader(Constants.HDR_VCLOCK, vclock); } // Serialize body if (httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; // Any value set using setValueAsStream() has precedent over value // set using setValue() if (valueStream != null) { if (valueStreamLength != null && valueStreamLength >= 0) { entityEnclosingMethod.setRequestEntity( new InputStreamRequestEntity(valueStream, valueStreamLength, contentType)); } else { entityEnclosingMethod.setRequestEntity(new InputStreamRequestEntity(valueStream, contentType)); } } else if (value != null) { entityEnclosingMethod.setRequestEntity(new ByteArrayRequestEntity(value, contentType)); } else { entityEnclosingMethod.setRequestEntity(new ByteArrayRequestEntity("".getBytes(), contentType)); } } }
From source file:com.tribune.uiautomation.testscripts.Photo.java
private void setParameters(EntityEnclosingMethod method, String newNamespace, String newSlug) throws FileNotFoundException { StringPart namespacePart = newNamespace == null ? new StringPart(NAMESPACE_PARAM, namespace) : new StringPart(NAMESPACE_PARAM, newNamespace); StringPart slugPart = newSlug == null ? new StringPart(SLUG_PARAM, slug) : new StringPart(SLUG_PARAM, newSlug); // next two lines annoying work around for this bug: // https://github.com/rack/rack/issues/186 namespacePart.setContentType(null);/*from ww w .j a va 2s .c o m*/ slugPart.setContentType(null); if (file != null) { File f = new File(file); Part[] parts = { namespacePart, slugPart, new FilePart(FILE_PARAM, f, IMAGE_CONTENT_TYPE, FilePart.DEFAULT_CHARSET) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); } else { Part[] parts = { namespacePart, slugPart }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); } }
From source file:com.esri.gpt.framework.http.HttpClientRequest.java
/** * Create the HTTP method./*from w w w . ja v a2s . c om*/ * <br/>A GetMethod will be created if the RequestEntity associated with * the ContentProvider is null. Otherwise, a PostMethod will be created. * @return the HTTP method */ private HttpMethodBase createMethod() throws IOException { HttpMethodBase method = null; MethodName name = this.getMethodName(); // make the method if (name == null) { if (this.getContentProvider() == null) { this.setMethodName(MethodName.GET); method = new GetMethod(this.getUrl()); } else { this.setMethodName(MethodName.POST); method = new PostMethod(this.getUrl()); } } else if (name.equals(MethodName.DELETE)) { method = new DeleteMethod(this.getUrl()); } else if (name.equals(MethodName.GET)) { method = new GetMethod(this.getUrl()); } else if (name.equals(MethodName.POST)) { method = new PostMethod(this.getUrl()); } else if (name.equals(MethodName.PUT)) { method = new PutMethod(this.getUrl()); } // write the request body if necessary if (this.getContentProvider() != null) { if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod eMethod = (EntityEnclosingMethod) method; RequestEntity eAdapter = getContentProvider() instanceof MultiPartContentProvider ? new MultiPartProviderAdapter(this, eMethod, (MultiPartContentProvider) getContentProvider()) : new ApacheEntityAdapter(this, this.getContentProvider()); eMethod.setRequestEntity(eAdapter); if (eAdapter.getContentType() != null) { eMethod.setRequestHeader("Content-type", eAdapter.getContentType()); } } else { // TODO: possibly will need an exception here in the future } } // set headers, add the retry method for (Map.Entry<String, String> hdr : this.requestHeaders.entrySet()) { method.addRequestHeader(hdr.getKey(), hdr.getValue()); } // declare possible gzip handling method.setRequestHeader("Accept-Encoding", "gzip"); this.addRetryHandler(method); return method; }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */// w w w. java 2s .c o m @SuppressWarnings("unchecked") public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string // part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:com.liferay.portal.util.HttpImpl.java
protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers, Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts, Map<String, String> parts, Http.Response response, boolean followRedirects) throws IOException { byte[] bytes = null; HttpMethod httpMethod = null;/*from w ww.j a va 2 s. c o m*/ HttpState httpState = null; try { _cookies.set(null); if (location == null) { return null; } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) { location = Http.HTTP_WITH_SLASH + location; } HostConfiguration hostConfiguration = getHostConfiguration(location); HttpClient httpClient = getClient(hostConfiguration); if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) { if (method.equals(Http.Method.POST)) { httpMethod = new PostMethod(location); } else { httpMethod = new PutMethod(location); } if (body != null) { RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(), body.getCharset()); EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; entityEnclosingMethod.setRequestEntity(requestEntity); } else if (method.equals(Http.Method.POST)) { PostMethod postMethod = (PostMethod) httpMethod; processPostMethod(postMethod, fileParts, parts); } } else if (method.equals(Http.Method.DELETE)) { httpMethod = new DeleteMethod(location); } else if (method.equals(Http.Method.HEAD)) { httpMethod = new HeadMethod(location); } else { httpMethod = new GetMethod(location); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } } if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null) || ((fileParts != null) && !fileParts.isEmpty()) | ((parts != null) && !parts.isEmpty()))) { } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED); } if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) { httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT); } httpState = new HttpState(); if ((cookies != null) && (cookies.length > 0)) { org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies); httpState.addCookies(commonsCookies); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (auth != null) { httpMethod.setDoAuthentication(true); httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword())); } proxifyState(httpState, hostConfiguration); httpClient.executeMethod(hostConfiguration, httpMethod, httpState); Header locationHeader = httpMethod.getResponseHeader("location"); if ((locationHeader != null) && !locationHeader.equals(location)) { String redirect = locationHeader.getValue(); if (followRedirects) { return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts, response, followRedirects); } else { response.setRedirect(redirect); } } InputStream inputStream = httpMethod.getResponseBodyAsStream(); if (inputStream != null) { Header contentLength = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH); if (contentLength != null) { response.setContentLength(GetterUtil.getInteger(contentLength.getValue())); } Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE); if (contentType != null) { response.setContentType(contentType.getValue()); } bytes = FileUtil.getBytes(inputStream); } for (Header header : httpMethod.getResponseHeaders()) { response.addHeader(header.getName(), header.getValue()); } return bytes; } finally { try { if (httpState != null) { _cookies.set(toServletCookies(httpState.getCookies())); } } catch (Exception e) { _log.error(e, e); } try { if (httpMethod != null) { httpMethod.releaseConnection(); } } catch (Exception e) { _log.error(e, e); } } }
From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java
private HttpMethodBase createMethod(HttpClient client, Request request) throws IOException, FileNotFoundException { String methodName = request.getMethod(); HttpMethodBase method = null;//from ww w .j av a2 s . c om if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) { EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl()) : new PutMethod(request.getUrl()); String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); post.getParams().setContentCharset("ISO-8859-1"); if (request.getByteData() != null) { post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData())); post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length)); } else if (request.getStringData() != null) { post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset)); post.setRequestHeader("Content-Length", String.valueOf(request.getStringData().getBytes(bodyCharset).length)); } else if (request.getStreamData() != null) { InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData()); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } else if (request.getParams() != null) { StringBuilder sb = new StringBuilder(); for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } post.setRequestHeader("Content-Length", String.valueOf(sb.length())); post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1")); if (!request.getHeaders().containsKey("Content-Type")) { post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(), post.getParams()); post.setRequestEntity(mre); post.setRequestHeader("Content-Type", mre.getContentType()); post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength())); } else if (request.getEntityWriter() != null) { post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(), computeAndSetContentLength(request, post))); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format(Thread.currentThread() + "File %s is not a file or doesn't exist", file.getAbsolutePath())); } post.setRequestHeader("Content-Length", String.valueOf(file.length())); FileInputStream fis = new FileInputStream(file); try { InputStreamRequestEntity r = new InputStreamRequestEntity(fis); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } finally { fis.close(); } } else if (request.getBodyGenerator() != null) { Body body = request.getBodyGenerator().createBody(); try { int length = (int) body.getContentLength(); if (length < 0) { length = (int) request.getContentLength(); } // TODO: This is suboptimal if (length >= 0) { post.setRequestHeader("Content-Length", String.valueOf(length)); // This is totally sub optimal byte[] bytes = new byte[length]; ByteBuffer buffer = ByteBuffer.wrap(bytes); for (;;) { buffer.clear(); if (body.read(buffer) < 0) { break; } } post.setRequestEntity(new ByteArrayRequestEntity(bytes)); } } finally { try { body.close(); } catch (IOException e) { logger.warn("Failed to close request body: {}", e.getMessage(), e); } } } if (request.getHeaders().getFirstValue("Expect") != null && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) { post.setUseExpectHeader(true); } method = post; } else if (methodName.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("HEAD")) { method = new HeadMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("GET")) { method = new GetMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("OPTIONS")) { method = new OptionsMethod(request.getUrl()); } else { throw new IllegalStateException(String.format("Invalid Method", methodName)); } ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer(); boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request); if (!avoidProxy) { if (proxyServer.getPrincipal() != null) { Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(), proxyServer.getPassword()); client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds); } ProxyHost proxyHost = proxyServer == null ? null : new ProxyHost(proxyServer.getHost(), proxyServer.getPort()); client.getHostConfiguration().setProxyHost(proxyHost); } method.setFollowRedirects(false); if ((request.getCookies() != null) && !request.getCookies().isEmpty()) { for (Cookie cookie : request.getCookies()) { method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies())); } } if (request.getHeaders() != null) { for (String name : request.getHeaders().keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : request.getHeaders().get(name)) { method.setRequestHeader(name, value); } } } } if (request.getHeaders().getFirstValue("User-Agent") != null) { method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { method.setRequestHeader("User-Agent", config.getUserAgent()); } else { method.setRequestHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class)); } if (config.isCompressionEnabled()) { Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding"); if (acceptableEncodingHeader != null) { String acceptableEncodings = acceptableEncodingHeader.getValue(); if (acceptableEncodings.indexOf("gzip") == -1) { StringBuilder buf = new StringBuilder(acceptableEncodings); if (buf.length() > 1) { buf.append(","); } buf.append("gzip"); method.setRequestHeader("Accept-Encoding", buf.toString()); } } else { method.setRequestHeader("Accept-Encoding", "gzip"); } } if (request.getVirtualHost() != null) { String vs = request.getVirtualHost(); int index = vs.indexOf(":"); if (index > 0) { vs = vs.substring(0, index); } method.getParams().setVirtualHost(vs); } return method; }
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);//ww w . j a v a 2 s .co m 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); } }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers, Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts, Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId, PortletRequest portletRequest) throws IOException { byte[] bytes = null; HttpMethod httpMethod = null;/* w w w . j a v a 2 s.com*/ HttpState httpState = null; try { _cookies.set(null); if (location == null) { return null; } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) { location = Http.HTTP_WITH_SLASH + location; } HostConfiguration hostConfiguration = getHostConfiguration(location); HttpClient httpClient = getClient(hostConfiguration); if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) { if (method.equals(Http.Method.POST)) { httpMethod = new PostMethod(location); } else { httpMethod = new PutMethod(location); } if (body != null) { RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(), body.getCharset()); EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; entityEnclosingMethod.setRequestEntity(requestEntity); } else if (method.equals(Http.Method.POST)) { PostMethod postMethod = (PostMethod) httpMethod; if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) { HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8); } processPostMethod(postMethod, fileParts, parts); } } else if (method.equals(Http.Method.DELETE)) { httpMethod = new DeleteMethod(location); } else if (method.equals(Http.Method.HEAD)) { httpMethod = new HeadMethod(location); } else { httpMethod = new GetMethod(location); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } } if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null) || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) { } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) { httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8); } if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) { httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT); } httpState = new HttpState(); if (ArrayUtil.isNotEmpty(cookies)) { org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies); httpState.addCookies(commonsCookies); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (auth != null) { httpMethod.setDoAuthentication(true); httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword())); } proxifyState(httpState, hostConfiguration); int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState); response.setResponseCode(responseCode); Header locationHeader = httpMethod.getResponseHeader("location"); if ((locationHeader != null) && !locationHeader.equals(location)) { String redirect = locationHeader.getValue(); if (followRedirects) { return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts, response, followRedirects, progressId, portletRequest); } else { response.setRedirect(redirect); } } InputStream inputStream = httpMethod.getResponseBodyAsStream(); if (inputStream != null) { int contentLength = 0; Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH); if (contentLengthHeader != null) { contentLength = GetterUtil.getInteger(contentLengthHeader.getValue()); response.setContentLength(contentLength); } Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE); if (contentType != null) { response.setContentType(contentType.getValue()); } if (Validator.isNotNull(progressId) && (portletRequest != null)) { ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream, contentLength, progressId); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream( contentLength); try { progressInputStream.readAll(unsyncByteArrayOutputStream); } finally { progressInputStream.clearProgress(); } bytes = unsyncByteArrayOutputStream.unsafeGetByteArray(); unsyncByteArrayOutputStream.close(); } else { bytes = FileUtil.getBytes(inputStream); } } for (Header header : httpMethod.getResponseHeaders()) { response.addHeader(header.getName(), header.getValue()); } return bytes; } finally { try { if (httpState != null) { _cookies.set(toServletCookies(httpState.getCookies())); } } catch (Exception e) { _log.error(e, e); } try { if (httpMethod != null) { httpMethod.releaseConnection(); } } catch (Exception e) { _log.error(e, e); } } }
From source file:fedora.test.api.TestRESTAPI.java
private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception { if (url == null || url.length() == 0) { throw new IllegalArgumentException("url must be a non-empty value"); } else if (!(url.startsWith("http://") || url.startsWith("https://"))) { url = getBaseURL() + url;//from www . j a v a 2s . c om } EntityEnclosingMethod httpMethod = null; try { if (method.equals("PUT")) { httpMethod = new PutMethod(url); } else if (method.equals("POST")) { httpMethod = new PostMethod(url); } else { throw new IllegalArgumentException("method must be one of PUT or POST."); } httpMethod.setDoAuthentication(authenticate); httpMethod.getParams().setParameter("Connection", "Keep-Alive"); if (requestContent != null) { httpMethod.setContentChunked(chunked); if (requestContent instanceof String) { httpMethod.setRequestEntity( new StringRequestEntity((String) requestContent, "text/xml", "utf-8")); } else if (requestContent instanceof File) { Part[] parts = { new StringPart("param_name", "value"), new FilePart(((File) requestContent).getName(), (File) requestContent) }; httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams())); } else { throw new IllegalArgumentException("requestContent must be a String or File"); } } getClient(authenticate).executeMethod(httpMethod); return new HttpResponse(httpMethod); } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same standard * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are * configuring to send a standard request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the data to be sent via the {@link EntityEnclosingMethod} */// www . jav a2 s. co m @SuppressWarnings("unchecked") private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws IOException { // Get the client POST data as a Map Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap(); // Create a List to hold the NameValuePairs to be passed to the PostMethod List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>(); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParamterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue); listNameValuePairs.add(nameValuePair); } } RequestEntity entity = null; String contentType = httpServletRequest.getContentType(); if (contentType != null) { contentType = contentType.toLowerCase(); if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application") || contentType.contains("text")) { String body = IOHelpers.readFully(httpServletRequest.getReader()); entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding()); entityEnclosingMethod.setRequestEntity(entity); } } NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {}); if (entity != null) { // TODO add as URL parameters? //postMethodProxyRequest.addParameters(parameters); } else { // Set the proxy request POST data if (entityEnclosingMethod instanceof PostMethod) { ((PostMethod) entityEnclosingMethod).setRequestBody(parameters); } } }