List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:httpmultiplexer.httpproxy.ProxyServlet.java
protected void duplicateRequest(HttpServletRequest servletRequest) throws ServletException, IOException { //initialize request attributes from caches if unset by a subclass by this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, secondTargetUri); }/*from w ww .j av a2s . c o m*/ if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, secondTargetHost); } // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest; //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { _logger.info("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyClient.getParams().setParameter("http.socket.timeout", 1000); proxyClient.getParams().setParameter("http.connection.timeout", 1000); proxyClient.getParams().setParameter("http.connection-manager.timeout", (long) 1000); proxyClient.execute(getTargetHost(servletRequest), proxyRequest); } catch (Exception e) { _logger.error("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri() + " got error " + e.toString()); } finally { servletRequest.setAttribute(ATTR_TARGET_URI, null); servletRequest.setAttribute(ATTR_TARGET_HOST, null); // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) { consumeQuietly(proxyResponse.getEntity()); } //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }
From source file:com.nkang.kxmoment.util.SolrUtils.HttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;/*from ww w . jav a 2 s .c om*/ InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add(new FormBodyPart(p, new StringBody(v, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // client already has this set, is this needed method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); // add jauth information //String username = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_USERNAME).toString(); //String password = WebServiceLoaderUtils.getWebServiceProperty(Constants.SECURITY_PASSWORD).toString(); ResourceBundle bundle = ResourceBundle.getBundle("solrconfig"); String username; String password; username = bundle.getString("wsUsername.url"); password = bundle.getString("wsPassword.url"); method.addHeader("username", username); method.addHeader("password", password); InputStream respBody = null; boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList<?> err = (NamedList<?>) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (IOException e) { //log.error("", e); } finally { if (!success) { method.abort(); } } } } }
From source file:org.mumod.util.HttpManager.java
private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam, File attachment) throws IOException, MustardException, AuthException { URI uri;//from w ww. j a va 2 s. co m try { uri = new URI(url); } catch (URISyntaxException e) { throw new IOException("Invalid URL."); } if (MustardApplication.DEBUG) Log.d("HTTPManager", "Requesting " + uri); HttpPost post = new HttpPost(uri); HttpResponse response; // create the multipart request and add the parts to it MultipartEntity requestContent = new MultipartEntity(); long len = attachment.length(); InputStream ins = new FileInputStream(attachment); InputStreamEntity ise = new InputStreamEntity(ins, -1L); byte[] data = EntityUtils.toByteArray(ise); String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG; requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName())); if (params != null) { for (NameValuePair param : params) { len += param.getValue().getBytes().length; requestContent.addPart(param.getName(), new StringBody(param.getValue())); } } post.setEntity(requestContent); Log.d("Mustard", "Length: " + len); if (mHeaders != null) { Iterator<String> headKeys = mHeaders.keySet().iterator(); while (headKeys.hasNext()) { String key = headKeys.next(); post.setHeader(key, mHeaders.get(key)); } } if (consumer != null) { try { consumer.sign(post); } catch (OAuthMessageSignerException e) { } catch (OAuthExpectationFailedException e) { } catch (OAuthCommunicationException e) { } } try { mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); response = mClient.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); throw new IOException("HTTP protocol error."); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new AuthException(401, "Unauthorized: " + url); } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) { try { JSONObject json = null; try { json = new JSONObject(StreamUtil.toString(response.getEntity().getContent())); } catch (JSONException e) { throw new MustardException(998, "Non json response: " + e.toString()); } throw new MustardException(statusCode, json.getString("error")); } catch (IllegalStateException e) { throw new IOException("Could not parse error response."); } catch (JSONException e) { throw new IOException("Could not parse error response."); } } else if (statusCode != 200) { Log.e("Mustard", response.getStatusLine().getReasonPhrase()); throw new MustardException(999, "Unmanaged response code: " + statusCode); } return response.getEntity().getContent(); }
From source file:org.mustard.util.HttpManager.java
private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam, File attachment) throws IOException, MustardException, AuthException { URI uri;// ww w . ja v a 2s . co m try { uri = new URI(url); } catch (URISyntaxException e) { throw new IOException("Invalid URL."); } if (MustardApplication.DEBUG) Log.d("HTTPManager", "Requesting " + uri); HttpPost post = new HttpPost(uri); HttpResponse response; // create the multipart request and add the parts to it MultipartEntity requestContent = new MultipartEntity(); long len = attachment.length(); InputStream ins = new FileInputStream(attachment); InputStreamEntity ise = new InputStreamEntity(ins, -1L); byte[] data = EntityUtils.toByteArray(ise); String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG; requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName())); if (params != null) { for (NameValuePair param : params) { len += param.getValue().getBytes().length; requestContent.addPart(param.getName(), new StringBody(param.getValue())); } } post.setEntity(requestContent); Log.d("Mustard", "Length: " + len); if (mHeaders != null) { Iterator<String> headKeys = mHeaders.keySet().iterator(); while (headKeys.hasNext()) { String key = headKeys.next(); post.setHeader(key, mHeaders.get(key)); } } if (consumer != null) { try { consumer.sign(post); } catch (OAuthMessageSignerException e) { } catch (OAuthExpectationFailedException e) { } catch (OAuthCommunicationException e) { } } try { mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); response = mClient.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); throw new IOException("HTTP protocol error."); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new AuthException(401, "Unauthorized: " + url); } else if (statusCode == 403 || statusCode == 406) { try { JSONObject json = null; try { json = new JSONObject(StreamUtil.toString(response.getEntity().getContent())); } catch (JSONException e) { throw new MustardException(998, "Non json response: " + e.toString()); } throw new MustardException(statusCode, json.getString("error")); } catch (IllegalStateException e) { throw new IOException("Could not parse error response."); } catch (JSONException e) { throw new IOException("Could not parse error response."); } } else if (statusCode != 200) { Log.e("Mustard", response.getStatusLine().getReasonPhrase()); throw new MustardException(999, "Unmanaged response code: " + statusCode); } return response.getEntity().getContent(); }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java
@SuppressWarnings("deprecation") @Override//from w w w . ja v a 2s. c o m public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) { HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); String path = PropertyExpander.expandProperties(context, request.getPath()); StringBuffer query = new StringBuffer(); String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding())); StringToStringMap responseProperties = (StringToStringMap) context .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES); MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType()) && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null; RestParamsPropertyHolder params = request.getParams(); for (int c = 0; c < params.getPropertyCount(); c++) { RestParamProperty param = params.getPropertyAt(c); String value = PropertyExpander.expandProperties(context, param.getValue()); responseProperties.put(param.getName(), value); List<String> valueParts = sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired()) ? RestUtils.splitMultipleParametersEmptyIncluded(value, request.getMultiValueDelimiter()) : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter()); // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by // the URI handling further down) if (value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) { try { if (StringUtils.hasContent(encoding)) { value = URLEncoder.encode(value, encoding); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding)); } else { value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } } catch (UnsupportedEncodingException e1) { SoapUI.logError(e1); value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } // URLEncoder replaces space with "+", but we want "%20". value = value.replaceAll("\\+", "%20"); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20")); } if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) { if (!StringUtils.hasContent(value) && !param.getRequired()) continue; } switch (param.getStyle()) { case HEADER: for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart); break; case QUERY: if (formMp == null || !request.isPostQueryString()) { for (String valuePart : valueParts) { if (query.length() > 0) query.append('&'); query.append(URLEncoder.encode(param.getName())); query.append('='); if (StringUtils.hasContent(valuePart)) query.append(valuePart); } } else { try { addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName())); } catch (MessagingException e) { SoapUI.logError(e); } } break; case TEMPLATE: try { value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } break; case MATRIX: try { value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } if (param.getType().equals(XmlBoolean.type.getName())) { if (value.toUpperCase().equals("TRUE") || value.equals("1")) { path += ";" + param.getName(); } } else { path += ";" + param.getName(); if (StringUtils.hasContent(value)) { path += "=" + value; } } case PLAIN: break; } } if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES)) path = PathUtils.fixForwardSlashesInPath(path); if (PathUtils.isHttpPath(path)) { try { // URI(String) automatically URLencodes the input, so we need to // decode it first... URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri); java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(), oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } else if (StringUtils.hasContent(path)) { try { java.net.URI oldUri = httpMethod.getURI(); String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath()) ? oldUri.getRawPath() + path : path; java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), pathToSet, oldUri.getQuery(), oldUri.getFragment()); httpMethod.setURI(newUri); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS))); } catch (Exception e) { SoapUI.logError(e); } } if (query.length() > 0 && !request.isPostQueryString()) { try { java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), oldUri.getRawPath(), query.toString(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } if (request instanceof RestRequest) { String acceptEncoding = ((RestRequest) request).getAccept(); if (StringUtils.hasContent(acceptEncoding)) { httpMethod.setHeader("Accept", acceptEncoding); } } if (formMp != null) { // create request message try { if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(), request.isEntitizeProperties()); if (StringUtils.hasContent(requestContent)) { initRootPart(request, requestContent, formMp); } } for (Attachment attachment : request.getAttachments()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); if (attachment instanceof FileAttachment<?>) { String name = attachment.getName(); if (StringUtils.hasContent(attachment.getContentID()) && !name.equals(attachment.getContentID())) name = attachment.getContentID(); part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\""); } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\""); part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment))); formMp.addBodyPart(part); } MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(formMp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue()); httpMethod.setHeader("MIME-Version", "1.0"); } catch (Throwable e) { SoapUI.logError(e); } } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { if (StringUtils.hasContent(request.getMediaType())) httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); if (request.isPostQueryString()) { try { ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString())); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } } else { String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(), request.isEntitizeProperties()); List<Attachment> attachments = new ArrayList<Attachment>(); for (Attachment attachment : request.getAttachments()) { if (attachment.getContentType().equals(request.getMediaType())) { attachments.add(attachment); } } if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) { try { byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding); ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content)); } catch (UnsupportedEncodingException e) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new ByteArrayEntity(requestContent.getBytes())); } } else if (attachments.size() > 0) { try { MimeMultipart mp = null; if (StringUtils.hasContent(requestContent)) { mp = new MimeMultipart(); initRootPart(request, requestContent, mp); } else if (attachments.size() == 1) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1)); httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); } if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) { if (mp == null) mp = new MimeMultipart(); // init mimeparts AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap()); // create request message MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(mp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding)); httpMethod.setHeader("MIME-Version", "1.0"); } } catch (Exception e) { SoapUI.logError(e); } } } } }
From source file:com.fuseim.webapp.ProxyServlet.java
protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri, HttpServletRequest servletRequest) throws IOException { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); String contentType = servletRequest.getContentType(); boolean isFormPost = (contentType != null && contentType.contains("application/x-www-form-urlencoded") && "POST".equalsIgnoreCase(servletRequest.getMethod())); if (isFormPost) { List<NameValuePair> params = new ArrayList<>(); List<NameValuePair> queryParams = Collections.emptyList(); String queryString = servletRequest.getQueryString(); if (queryString != null) { URLEncodedUtils.parse(queryString, Consts.UTF_8); }/*from w ww . j av a 2 s . co m*/ Map<String, String[]> form = servletRequest.getParameterMap(); OUTER_LOOP: for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) { String name = nameIterator.next(); for (NameValuePair queryParam : queryParams) { if (name.equals(queryParam.getName())) { continue OUTER_LOOP; } } String[] value = form.get(name); if (value.length != 1) { throw new RuntimeException("expecting one value in post form"); } params.add(new BasicNameValuePair(name, value[0])); } eProxyRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } else { eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), getContentLength(servletRequest))); } return eProxyRequest; }
From source file:com.fujitsu.dc.client.http.DcRequestBuilder.java
/** * This method is used to generate a HttpUriRequest object by setting the parameters in request header. * @return HttpUriRequest object that is generated * @throws DaoException Exception thrown *//*from w w w . ja va2 s . c om*/ public HttpUriRequest build() throws DaoException { HttpUriRequest req = null; if (HttpMethods.PUT.equals(this.methodValue)) { req = new HttpPut(this.urlValue); } else if (HttpMethods.POST.equals(this.methodValue)) { req = new HttpPost(this.urlValue); } else if (HttpMethods.DELETE.equals(this.methodValue)) { req = new HttpDelete(this.urlValue); } else if (HttpMethods.ACL.equals(this.methodValue)) { req = new HttpAclMethod(this.urlValue); } else if (HttpMethods.MKCOL.equals(this.methodValue)) { req = new HttpMkColMethod(this.urlValue); } else if (HttpMethods.PROPPATCH.equals(this.methodValue)) { req = new HttpPropPatchMethod(this.urlValue); } else if (HttpMethods.PROPFIND.equals(this.methodValue)) { req = new HttpPropfindMethod(this.urlValue); } else if (HttpMethods.GET.equals(this.methodValue)) { req = new HttpGet(this.urlValue); } else if (HttpMethods.MERGE.equals(this.methodValue)) { req = new HttpMergeMethod(this.urlValue); } if (this.tokenValue != null) { req.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.tokenValue); } /** include header parameters if any. */ for (String key : headers.keySet()) { String value = headers.get(key); req.addHeader(key, value); } // ???????? /** If Default header is set, configure them. */ // ????????????????????? /** * The reason you do not want to set for the first time, since the request header, would have been more than one * registration is the same name header */ if (this.defaultHeaders != null) { for (String key : this.defaultHeaders.keySet()) { String val = this.defaultHeaders.get(key); Header[] headerItems = req.getHeaders(key); if (headerItems.length == 0) { req.addHeader(key, val); } } } if (this.bodyValue != null) { HttpEntity body = null; try { if (this.getContentType() != "" && RestAdapter.CONTENT_TYPE_JSON.equals(this.getContentType())) { String bodyStr = toUniversalCharacterNames(this.bodyValue); body = new StringEntity(bodyStr); } else { body = new StringEntity(this.bodyValue, RestAdapter.ENCODE); } } catch (UnsupportedEncodingException e) { throw DaoException.create("error while request body encoding : " + e.getMessage(), 0); } ((HttpEntityEnclosingRequest) req).setEntity(body); } if (this.bodyStream != null) { InputStreamEntity body = new InputStreamEntity(this.bodyStream, -1); body.setChunked(true); this.bodyValue = "[stream]"; ((HttpEntityEnclosingRequest) req).setEntity(body); } if (req != null) { log.debug(""); log.debug("?Request " + req.getMethod() + " " + req.getURI()); Header[] allheaders = req.getAllHeaders(); for (int i = 0; i < allheaders.length; i++) { log.debug("RequestHeader[" + allheaders[i].getName() + "] : " + allheaders[i].getValue()); } log.debug("RequestBody : " + bodyValue); } return req; }
From source file:sk.datalan.solr.impl.HttpSolrServer.java
protected HttpRequestBase createMethod(final SolrRequest request) throws IOException, SolrServerException { HttpRequestBase method = null;/*from ww w . j a v a2 s . c om*/ InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add( new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8)); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } return method; }