List of usage examples for org.apache.http.entity.mime.content InputStreamBody InputStreamBody
public InputStreamBody(final InputStream in, final String mimeType, final String filename)
From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java
@Override protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input, String fileName, String mimeType) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;//from w w w. ja v a 2s . c o m if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml) : null; HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntity requestMultipartEntity = new MultipartEntity(); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept", "application/xml"); // add xml part to the multipart entity if (xml != null) { //StringBody xmlPart = new StringBody( // xml, "application/xml; name=body.xml", Charset.forName( getEncoding() ) ); InputStreamBody xmlPart = new InputStreamBody(new ByteArrayInputStream(xml.getBytes(getEncoding())), "application/xml", "body.xml"); requestMultipartEntity.addPart("metadata", xmlPart); } // add file part to the multipart entity if (input != null) { mimeType = StringUtils.trimToNull(mimeType); if (mimeType == null) mimeType = "application/octet-stream"; fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; InputStreamBody filePart = new InputStreamBody(input, mimeType, fileName); requestMultipartEntity.addPart("attachment", filePart); } // add multipart entity to the request ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request getAuthConsumer().sign(request); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java
private static HttpEntity multipartEntity(String attachmentFileName, InputStream attachmentContent) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); InputStreamBody inputStreamBody;/*from www.java2 s.c om*/ if (isNotBlank(attachmentFileName)) { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM, attachmentFileName); } else { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM); } multipartEntityBuilder.addPart("file", inputStreamBody); return multipartEntityBuilder.build(); }
From source file:org.coronastreet.gpxconverter.GarminForm.java
public void upload() { httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { try {//from ww w . j a v a 2 s . c o m HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#"); HttpResponse formResponse = httpClient.execute(get, localContext); HttpEntity formEntity = formResponse.getEntity(); EntityUtils.consume(formEntity); HttpPost request = new HttpPost( "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx"); request.setHeader("Referer", "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1"); request.setHeader("Accept", "text/html, application/xhtml+xml, */*"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); output = "[" + output + "]"; //OMG Garmin Sucks at JSON..... JSONObject uploadResponse = new JSONArray(output).getJSONObject(0); JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult"); try { int uploadID = importResult.getInt("uploadId"); log("Success! UploadID is " + uploadID); } catch (Exception e) { JSONArray failures = (JSONArray) importResult.get("failures"); JSONObject failure = (JSONObject) failures.get(0); JSONArray errorMessages = failure.getJSONArray("messages"); JSONObject errorMessage = errorMessages.getJSONObject(0); String content = errorMessage.getString("content"); log("Upload Failed! Error: " + content); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }
From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java
static private void addPart(MultipartEntity multipartEntity, InputStream inputStream, Element element, String url) {//ww w.j av a2 s . c o m // Gather mediatype and filename if known // NOTE: special MIP-like annotations were added just before re-rooting/pruning element. Those will be // removed during the next recalculate. // See this WG action item (which was decided but not carried out): "Clarify that upload activation produces // content and possibly filename and mediatype info as metadata. If available, filename and mediatype are copied // to instance data if upload filename and mediatype elements are specified. At serialization, filename and // mediatype from instance data are used if upload filename and mediatype are specified; otherwise, filename and // mediatype are drawn from upload metadata, if they were available at time of upload activation" // // See: // http://lists.w3.org/Archives/Public/public-forms/2009May/0052.html // http://lists.w3.org/Archives/Public/public-forms/2009Apr/att-0010/2009-04-22.html#ACTION2 // // See also this clarification: // http://lists.w3.org/Archives/Public/public-forms/2009May/0053.html // http://lists.w3.org/Archives/Public/public-forms/2009Apr/att-0003/2009-04-01.html#ACTION1 // // The bottom line is that if we can find the xf:upload control bound to a node to submit, we try to get // metadata from that control. If that fails (which can be because the control is non-relevant, bound to another // control, or never had nested xf:filename/xf:mediatype elements), we try URL metadata. URL metadata is only // present on nodes written by xf:upload as temporary file: URLs. It is not present if the data is stored as // xs:base64Binary. In any case, metadata can be absent. // // If an xf:upload control saved data to a node as xs:anyURI, has xf:filename/xf:mediatype elements, is still // relevant and bound to the original node (as well as its children elements), and if the nodes pointed to by // the children elements have not been modified (e.g. by xf:setvalue), then retrieving the metadata via // xf:upload should be equivalent to retrieving it via the URL metadata. // // Benefits of URL metadata: a single xf:upload can be used to save data to multiple nodes over time, and it // doesn't have to be relevant and bound upon submission. // // Benefits of using xf:upload metadata: it is possible to modify the filename and mediatype subsequently. // // URL metadata was added 2012-05-29. // Get mediatype, first via xf:upload control, or, if not found, try URL metadata String mediatype = InstanceData.getTransientAnnotation(element, "xxforms-mediatype"); if (mediatype == null && url != null) mediatype = XFormsUploadControl.getParameterOrNull(url, "mediatype"); // Get filename, first via xf:upload control, or, if not found, try URL metadata String filename = InstanceData.getTransientAnnotation(element, "xxforms-filename"); if (filename == null && url != null) filename = XFormsUploadControl.getParameterOrNull(url, "filename"); final ContentBody contentBody = new InputStreamBody(inputStream, mediatype, filename); multipartEntity.addPart(element.getName(), contentBody); }
From source file:com.puppetlabs.puppetdb.javaclient.impl.HttpComponentsConnector.java
@Override public <V> V postUpload(String uri, Map<String, String> stringParts, InputStream in, String mimeType, String fileName, final long fileSize, Class<V> type) throws IOException { HttpPost request = new HttpPost(createURI(uri)); configureRequest(request);/*from www .j a va2s. co m*/ MultipartEntity entity = new MultipartEntity(); for (Map.Entry<String, String> entry : stringParts.entrySet()) entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8)); entity.addPart("file", new InputStreamBody(in, mimeType, fileName) { @Override public long getContentLength() { return fileSize; } }); request.setEntity(entity); return executeRequest(request, type, null); }
From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java
/** * uploads measurements data as a batch file * @param dbIterator/* ww w . j av a 2 s.c o m*/ * @param latLonFormat * @param count * @param max * @return number of uploaded measurements */ private int uploadMeasurementsBatch(MeasurementsDBIterator dbIterator, NumberFormat latLonFormat, int count, int max) { writeToLog("uploadMeasurementsBatch(" + count + ", " + max + ")"); try { StringBuilder sb = new StringBuilder( "lat,lon,mcc,mnc,lac,cellid,signal,measured_at,rating,speed,direction,act\n"); int thisBatchSize = 0; while (thisBatchSize < MEASUREMENTS_BATCH_SIZE && dbIterator.hasNext() && uploadThreadRunning) { Measurement meassurement = dbIterator.next(); sb.append(latLonFormat.format(meassurement.getLat())).append(","); sb.append(latLonFormat.format(meassurement.getLon())).append(","); sb.append(meassurement.getMcc()).append(","); sb.append(meassurement.getMnc()).append(","); sb.append(meassurement.getLac()).append(","); sb.append(meassurement.getCellid()).append(","); sb.append(meassurement.getGsmSignalStrength()).append(","); sb.append(meassurement.getTimestamp()).append(","); sb.append((meassurement.getAccuracy() != null) ? meassurement.getAccuracy() : "").append(","); sb.append((int) meassurement.getSpeed()).append(","); sb.append((int) meassurement.getBearing()).append(","); sb.append((meassurement.getNetworkType() != null) ? meassurement.getNetworkType() : ""); sb.append("\n"); thisBatchSize++; } HttpResponse response = null; writeToLog("Upload request URL: " + httppost.getURI()); if (uploadThreadRunning) { String csv = sb.toString(); writeToLog("Upload data: " + csv); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("key", new StringBody(apiKey)); mpEntity.addPart("appId", new StringBody(appId)); mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(csv.getBytes()), "text/csv", MULTIPART_FILENAME)); ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); // reqEntity is the MultipartEntity instance mpEntity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(mpEntity.getContentEncoding()); bArrEntity.setContentType(mpEntity.getContentType()); httppost.setEntity(bArrEntity); response = httpclient.execute(httppost); if (response == null) { writeToLog("Upload: null HTTP-response"); throw new IllegalStateException("no HTTP-response from server"); } HttpEntity resEntity = response.getEntity(); writeToLog( "Upload: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine()); if (resEntity != null) { resEntity.consumeContent(); } if (response.getStatusLine() == null) { writeToLog(": " + "null HTTP-status-line"); throw new IllegalStateException("no HTTP-status returned"); } if (response.getStatusLine().getStatusCode() != 200) { throw new IllegalStateException( "HTTP-status code returned : " + response.getStatusLine().getStatusCode()); } } return count + thisBatchSize; } catch (IOException e) { throw new IllegalStateException("IO-Error: " + e.getMessage()); } }
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;/* ww w . ja v a2 s . co m*/ 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.gitana.platform.client.support.RemoteImpl.java
@Override public void upload(String uri, InputStream in, long length, String mimetype, String filename) throws Exception { String URL = buildURL(uri, false); HttpPost httpPost = new HttpPost(URL); InputStreamBody inputStreamBody = new InputStreamBody(in, mimetype, filename); MultipartEntity entity = new MultipartEntity(); entity.addPart(filename, inputStreamBody); httpPost.setEntity(entity);/* w w w.ja v a 2 s. c o m*/ HttpResponse httpResponse = invoker.execute(httpPost); if (!HttpUtil.isOk(httpResponse)) { throw new RuntimeException("Upload failed: " + EntityUtils.toString(httpResponse.getEntity())); } // consume the response fully so that the client connection can be reused EntityUtils.consume(httpResponse.getEntity()); }
From source file:sk.datalan.solr.impl.HttpSolrServer.java
protected HttpRequestBase createMethod(final SolrRequest request) throws IOException, SolrServerException { HttpRequestBase method = null;//from w ww . j a va2s.co m 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; }