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.apache.sling.scripting.sightly.it.SlingSpecificsSightlyIT.java
private void uploadFile(String fileName, String serverFileName, String url) throws IOException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(launchpadURL + url); post.setHeader("Authorization", "Basic YWRtaW46YWRtaW4="); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); InputStreamBody inputStreamBody = new InputStreamBody( this.getClass().getClassLoader().getResourceAsStream(fileName), ContentType.TEXT_PLAIN, fileName); entityBuilder.addPart(serverFileName, inputStreamBody); post.setEntity(entityBuilder.build()); httpClient.execute(post);/*www.j av a 2s . c om*/ }
From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java
/** * Used to upload entries from networks table to OCID servers. *//*from www. j av a 2 s . c om*/ private void uploadNetworks() { writeToLog("uploadNetworks()"); String existingFileName = "uploadNetworks.csv"; String data = null; NetworkDBIterator dbIterator = mDatabase.getNonUploadedNetworks(); try { if (dbIterator.getCount() > 0) { //timestamp, mcc, mnc, net (network type), nen (network name) StringBuilder sb = new StringBuilder("timestamp,mcc,mnc,net,nen" + ((char) 0xA)); while (dbIterator.hasNext() && uploadThreadRunning) { Network network = dbIterator.next(); sb.append(network.getTimestamp()).append(","); sb.append(network.getMcc()).append(","); sb.append(network.getMnc()).append(","); sb.append(network.getType()).append(","); sb.append(network.getName()); sb.append(((char) 0xA)); } data = sb.toString(); } else { writeToLog("No networks for upload."); return; } } finally { dbIterator.close(); } writeToLog("uploadNetworks(): " + data); if (uploadThreadRunning) { try { httppost = new HttpPost(networksUrl); HttpResponse response = null; writeToLog("Upload request URL: " + httppost.getURI()); if (uploadThreadRunning) { MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("apikey", new StringBody(apiKey)); mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(data.getBytes()), "text/csv", existingFileName)); 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("Response: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine()); if (resEntity != null) { writeToLog("Response content: " + EntityUtils.toString(resEntity)); resEntity.consumeContent(); } } if (uploadThreadRunning) { if (response == null) { writeToLog(": " + "null response"); throw new IllegalStateException("no response"); } if (response.getStatusLine() == null) { writeToLog(": " + "null HTTP-status-line"); throw new IllegalStateException("no HTTP-status returned"); } if (response.getStatusLine().getStatusCode() == 200) { mDatabase.setAllNetworksUploaded(); } else if (response.getStatusLine().getStatusCode() != 200) { throw new IllegalStateException( response.getStatusLine().getStatusCode() + " HTTP-status returned"); } } } catch (Exception e) { // httppost cancellation throws exceptions if (uploadThreadRunning) { writeExceptionToLog(e); } } } }
From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java
protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException { SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH;/* www . ja v a2s .c o m*/ } 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); } String basePath = baseUrl; if (collection != null) basePath += "/" + collection; if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } return new HttpGet(basePath + path + wparams.toQueryString()); } if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) { String url = basePath + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName; LinkedList<NameValuePair> postOrPutParams = new LinkedList<>(); if (streams == null || isMultipart) { // send server list and request list as query string params ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams); queryParams.add(calculateQueryParams(request.getQueryParams(), wparams)); String fullQueryUrl = url + queryParams.toQueryString(); HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl); if (!isMultipart) { postOrPut.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 { postOrPutParams.add(new BasicNameValuePair(p, v)); } } } } // TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder} 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); } postOrPut.setEntity(entity); } else { //not using multipart postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8)); } return postOrPut; } // It is has one stream, it is the post body, put the params in the URL else { String fullQueryUrl = url + wparams.toQueryString(); HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl); // 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) { Long size = contentStream[0].getSize(); postOrPut.setEntity( new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { Long size = contentStream[0].getSize(); postOrPut.setEntity( new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } return postOrPut; } } throw new SolrServerException("Unsupported method: " + request.getMethod()); }
From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java
void buildFilePart(final KeyDataPair pairWithFile, final MultipartEntityBuilder builder) throws IOException { String mimeType = pairWithFile.getMimeType(); if (mimeType == null) { mimeType = "application/octet-stream"; }/*from ww w . j a v a 2s . c o m*/ final ContentType contentType = ContentType.create(mimeType); final File file = pairWithFile.getFile(); if (pairWithFile.getData() != null) { final String filename; if (file == null) { filename = pairWithFile.getValue(); } else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) { filename = file.getAbsolutePath(); } else { filename = file.getName(); } builder.addBinaryBody(pairWithFile.getName(), new ByteArrayInputStream(pairWithFile.getData()), contentType, filename); return; } if (file == null) { builder.addPart(pairWithFile.getName(), // Overridden in order not to have a chunked response. new InputStreamBody(new ByteArrayInputStream(new byte[0]), contentType, pairWithFile.getValue()) { @Override public long getContentLength() { return 0; } }); return; } String filename; if (pairWithFile.getFile() == null) { filename = pairWithFile.getValue(); } else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) { filename = pairWithFile.getFile().getAbsolutePath(); } else { filename = pairWithFile.getFile().getName(); } builder.addBinaryBody(pairWithFile.getName(), pairWithFile.getFile(), contentType, filename); }
From source file:com.stepsdk.android.api.APIClient.java
private MultipartEntity addFile(MultipartEntity mpEntity, String key, String fromPath) throws IOException { String filepath;/*from w w w. ja v a 2 s .com*/ try { filepath = URLDecoder.decode(fromPath, "UTF-8"); // handle special character } catch (Exception e) { filepath = fromPath; } String fromFilename = filepath.substring(filepath.lastIndexOf("/") + 1); String filename = ""; long filesize = 0; ContentBody cbFile = null; log(TAG, "from upload path: " + fromPath); // upload from content uri if (fromPath.indexOf("content://") > -1) { Uri uri = Uri.parse(fromPath); String mime = mContext.getContentResolver().getType(uri); String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime); String mediatype = mime.substring(0, mime.indexOf('/')); InputStream is = mContext.getContentResolver().openInputStream(uri); filesize = is.available(); filename = mediatype + fromFilename + "." + extension; cbFile = new InputStreamBody(is, mime, filename); } else { //upload from file uri File file = new File(filepath); filesize = file.length(); filename = fromFilename; cbFile = new FileBody(file, FileUtil.getMimeTypeFromFilePath(fromPath)); } //final String finalfilename = filename; final long finalfilesize = filesize; //final int task_id = params[1].getIntExtra("cancel_task_id", 0); //final Intent cancelintent = params[1]; //final Intent doneintent = params[2]; mpEntity.addPart(key, cbFile); return mpEntity; }
From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java
private JobInfo send(final File metadataFile, final BinaryData binaryData, final Collection<File> studyFiles, final StudyQueryInfo studyQueryInfo) throws IOException, SAXException { final HttpPost httpPost = new HttpPost(studyQueryInfo == null ? createURI : updateURI); final MultipartEntity entity = new MultipartEntity(); if (studyQueryInfo != null) { entity.addPart(HttpMessagePart.STUDY_UUID.toString(), new StringBody(studyQueryInfo.studyUUID)); }/*from w w w . ja v a 2 s . co m*/ final StudyMetadata study = useXMLNotGPB ? StudyIO.parseFromXML(metadataFile) : StudyIO.parseFromGPB(metadataFile); if (studyQueryInfo != null) { //Specify current study version entity.addPart(HttpMessagePart.OLD_VERSION.toString(), new StringBody(studyQueryInfo.studyVersion)); } //Pretty significant in-memory operations, so scoping to get references released ASAP { final byte[] metaInBuffer; { final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(10000); if (useXMLNotGPB) { StudyIO.writeToXML(study, metaOut); } else { StudyIO.writeToGPB(study, metaOut); } metaInBuffer = metaOut.toByteArray(); } final ByteArrayInputStream metaIn = new ByteArrayInputStream(metaInBuffer); //We must distinguish MIME types for GPB vs. XML so that the server can handle them properly entity.addPart(metadataFile.getName(), new InputStreamBody(metaIn, useXMLNotGPB ? "text/xml" : "application/octet-stream", metadataFile.getName())); } //We support only one type assert binaryData instanceof BinaryDcmData; { int i = 0; for (final InputStream binaryStream : iter(((BinaryDcmData) binaryData).streamIterator())) { final String fileName = "binary" + i++; entity.addPart(fileName, new InputStreamBody(binaryStream, fileName)); } } //Debugging only // int i = 0; // for (final InputStream binaryStream: Iter.iter(((BinaryDcmData) binaryData).streamIterator())) { // final OutputStream testout = new BufferedOutputStream(new FileOutputStream("E:/testdata/" + i), 10000); // for(;;) { // final int val = binaryStream.read(); // if (val == -1) { // break; // } // testout.write(val); // } // testout.close(); // ++i; // } httpPost.setEntity(entity); final String response = httpClient.execute(httpPost, new BasicResponseHandler()); final long uploadEndTime = System.currentTimeMillis(); LOG.debug("Server response:" + response); final String jobID; final String studyID; final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes())); try { jobID = xPath.evaluate("/jobStatus/@jobID", responseDoc).trim(); studyID = xPath.evaluate("/jobStatus/@studyUUID", responseDoc).trim(); } catch (final XPathExpressionException e) { //This shouldn't happen throw new RuntimeException(e); } final JobInfo jobInfo = new JobInfo(jobID, studyID, studyFiles, uploadEndTime); jobIDInfo.put(jobID, jobInfo); return jobInfo; }
From source file:org.apache.solr.client.solrj.impl.HttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;/*from w ww . j av a 2s . 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); } // XXX client already has this set, is this needed? method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); 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 (Throwable t) { } // ignore if (!success) { method.abort(); } } } }
From source file:org.coronastreet.gpxconverter.StravaForm.java
public void upload() { //httpClient = new DefaultHttpClient(); 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()) { //log("Ok....logged in..."); try {//from w w w . ja v a 2s . c om // Have to fetch the form to get the CSRF Token HttpGet get = new HttpGet(uploadFormURL); HttpResponse formResponse = httpClient.execute(get, localContext); //log("Fetched the upload form...: " + formResponse.getStatusLine()); org.jsoup.nodes.Document doc = Jsoup.parse(EntityUtils.toString(formResponse.getEntity())); String csrftoken, csrfparam; Elements metalinksParam = doc.select("meta[name=csrf-param]"); if (!metalinksParam.isEmpty()) { csrfparam = metalinksParam.first().attr("content"); } else { csrfparam = null; log("Missing csrf-param?"); } Elements metalinksToken = doc.select("meta[name=csrf-token]"); if (!metalinksToken.isEmpty()) { csrftoken = metalinksToken.first().attr("content"); } else { csrftoken = null; log("Missing csrf-token?"); } HttpPost request = new HttpPost(uploadURL); request.setHeader("X-CSRF-Token", csrftoken); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("method", new StringBody("post")); entity.addPart("new_uploader", new StringBody("1")); entity.addPart(csrfparam, new StringBody(csrftoken)); entity.addPart("files[]", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding, and Strava doesn't support chunked. 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); //log(output); JSONObject userInfo = new JSONArray(output).getJSONObject(0); //log("Object: " + userInfo.toString()); if (userInfo.get("workflow").equals("Error")) { log("Upload Error: " + userInfo.get("error")); } else { log("Successful Uploaded. ID is " + userInfo.get("id")); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }