public static int sendPostMultipart(String urlString, Map<String, String> parameters) throws IOException { MultipartContent postBody = new MultipartContent() .setMediaType(new HttpMediaType("multipart/form-data")); postBody.setBoundary(MULTIPART_BOUNDARY); for (Map.Entry<String, String> entry : parameters.entrySet()) { HttpContent partContent = ByteArrayContent.fromString( // uses UTF-8 internally null /* part Content-Type */, entry.getValue()); HttpHeaders partHeaders = new HttpHeaders() .set("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""); postBody.addPart(new MultipartContent.Part(partHeaders, partContent)); } GenericUrl url = new GenericUrl(new URL(urlString)); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody); request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT)); request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS); request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS); HttpResponse response = request.execute(); return response.getStatusCode(); }
/** * Upload a file and attach it to a task * * @param task Globally unique identifier for the task. * @param fileContent Content of the file to be uploaded * @param fileName Name of the file to be uploaded * @param fileType MIME type of the file to be uploaded * @return Request object */ public ItemRequest<Attachment> createOnTask(String task, InputStream fileContent, String fileName, String fileType) { MultipartContent.Part part = new MultipartContent.Part() .setContent(new InputStreamContent(fileType, fileContent)) .setHeaders(new HttpHeaders().set( "Content-Disposition", String.format("form-data; name=\"file\"; filename=\"%s\"", fileName) // TODO: escape fileName? )); MultipartContent content = new MultipartContent() .setMediaType(new HttpMediaType("multipart/form-data").setParameter("boundary", UUID.randomUUID().toString())) .addPart(part); String path = String.format("/tasks/%s/attachments", task); return new ItemRequest<Attachment>(this, Attachment.class, path, "POST") .data(content); }
/** * <p>Created and returns a valid {@link MultipartContent} instance * that contains data required for submission.</p> * * @param input Input file to submit solution for. * @param output Output file produced by the algorithm. * @param source Source code file of the algorithm to submit. * @return Created multipart content. */ private MultipartContent createContent(final ProblemInput input, final File output, final File source) throws IOException { final HttpMediaType type = new HttpMediaType(MEDIA_TYPE); type.setParameter(BOUNDARY, createBoundary()); // Submission from Chrome through contest website sends fake path for security, // which presumes the server only uses the last token to generate the downloadable // zip. It is possible to submit real path here (source.getAbsolutePath) but to // preserve user privacy a fake path will do source.getName() might be sufficient // as well but it's not tested using a fake path is the safest option since that's // what Chrome does. final String sourceFilePath = new StringBuilder(PATH_PREFIX) .append(source.getName()) .toString(); final MultipartContent content = new MultipartContent() .setMediaType(type) .addPart(HttpRequestExecutor.buildDataPart(CSRF_PARAMETER_NAME, values.getToken())) .addPart(HttpRequestExecutor.buildFilePart(ANSWER_PARAMETER, output)) .addPart(HttpRequestExecutor.buildFilePart(SOURCE_FILE_PARAMETER, source)) .addPart(HttpRequestExecutor.buildDataPart(SOURCE_FILE_NAME_PARAMETER, sourceFilePath)) .addPart(HttpRequestExecutor.buildDataPart(COMMAND_PARAMETER_NAME, SUBMIT_COMMAND)) .addPart(HttpRequestExecutor.buildDataPart(PROBLEM_PARAMETER_NAME, input.getProblem().getId())) .addPart(HttpRequestExecutor.buildDataPart(INPUT_ID_PARAMETER_NAME, String.valueOf(input.getNumber()))) .addPart(HttpRequestExecutor.buildDataPart(NUM_SOURCE_FILE_PARAMETER, DEFAULT_NUM_SOURCE_FILE)) .addPart(HttpRequestExecutor.buildDataPart(AGENT_PARAMETER_NAME, DEFAULT_AGENT)); return content; }
/** * This method handles the final upload to the * {@link SteemJImageUploadConfig#getSteemitImagesEndpoint() * SteemitImagesEndpoint}. * * @param accountName * The Steem account used to sign the upload. * @param signature * The signature for this upload. * @param fileToUpload * The image to upload. * @return A URL object that contains the download URL of the image. * @throws HttpResponseException * In case the * {@link SteemJImageUploadConfig#getSteemitImagesEndpoint() * SteemitImagesEndpoint} returned an error. */ private static URL executeMultipartRequest(AccountName accountName, String signature, File fileToUpload) throws IOException { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); MultipartContent content = new MultipartContent().setMediaType(new HttpMediaType("multipart/form-data") .setParameter("boundary", "----WebKitFormBoundaryaAsqCuJ0UrJUS0dz")); FileContent fileContent = new FileContent(URLConnection.guessContentTypeFromName(fileToUpload.getName()), fileToUpload); MultipartContent.Part part = new MultipartContent.Part(fileContent); part.setHeaders(new HttpHeaders().set("Content-Disposition", String.format("form-data; name=\"image\"; filename=\"%s\"", fileToUpload.getName()))); content.addPart(part); HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer()) .buildPostRequest(new GenericUrl(SteemJImageUploadConfig.getInstance().getSteemitImagesEndpoint() + "/" + accountName.getName() + "/" + signature), content); LOGGER.debug("{} {}", httpRequest.getRequestMethod(), httpRequest.getUrl().toURI()); HttpResponse httpResponse = httpRequest.execute(); LOGGER.debug("{} {} {} ({})", httpResponse.getRequest().getRequestMethod(), httpResponse.getRequest().getUrl().toURI(), httpResponse.getStatusCode(), httpResponse.getStatusMessage()); ObjectMapper objectMapper = new ObjectMapper(); JsonNode response = objectMapper.readTree(httpResponse.parseAsString()); return new URL(response.get("url").asText()); }
public PhotoEntry executeInsertPhotoEntryWithMetadata( PhotoEntry photo, PicasaUrl albumFeedUrl, AbstractInputStreamContent content) throws IOException { HttpRequest request = getRequestFactory().buildPostRequest(albumFeedUrl, null); AtomContent atomContent = AtomContent.forEntry(DICTIONARY, photo); request.setContent(new MultipartContent().setContentParts(Arrays.asList(atomContent, content))); request.getHeaders().setMimeVersion("1.0"); return execute(request).parseAs(PhotoEntry.class); }
/** * Direct Uploads the media. * * @param initiationRequestUrl * The request URL where the initiation request will be sent * @return HTTP response */ private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); HttpContent content = mediaContent; if (metadata != null) { content = new MultipartContent().setContentParts(Arrays.asList( metadata, mediaContent)); initiationRequestUrl.put("uploadType", "multipart"); } else { initiationRequestUrl.put("uploadType", "media"); } HttpRequest request = requestFactory.buildRequest( initiationRequestMethod, initiationRequestUrl, content); request.getHeaders().putAll(initiationHeaders); // We do not have to do anything special here if media content length is // unspecified because // direct media upload works even when the media content length == -1. HttpResponse response = executeCurrentRequest(request); boolean responseProcessed = false; try { if (isMediaLengthKnown()) { totalBytesServerReceived = getMediaContentLength(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); responseProcessed = true; } finally { if (!responseProcessed) { response.disconnect(); } } return response; }
public PhotoEntry executeInsertPhotoEntryWithMetadata( PhotoEntry photo, PicasaUrl albumFeedUrl, InputStreamContent content, GmlPoint point) throws IOException { GeorssWhere georss = new GeorssWhere(); georss.point = point; photo.georssWhere = georss; HttpRequest request = getRequestFactory().buildPostRequest(albumFeedUrl, null); AtomContent atomContent = AtomContent.forEntry(DICTIONARY, photo); request.setContent(new MultipartContent().setContentParts(Arrays.asList(atomContent, content))); request.getHeaders().setMimeVersion("1.0"); return execute(request).parseAs(PhotoEntry.class); }
/** * <p>Submits the given <tt>output</tt> file and the * given <tt>source</tt> file for the given problem * <tt>input</tt>. This method should be call only * after a successful call to the {@link #download(ProblemInput)} * method on the same <tt>input</tt>, as the evaluation * system will judge the last downloaded dataset * based on the internal token / session.</p> * * @param input Input file to submit solution for. * @param output Output file produced by the algorithm. * @param source Source code file of the algorithm to submit. * @return Request response, as a {@link SubmitResponse} instance. * @throws IOException If any error occurs while uploading data, or performing the request. */ public SubmitResponse submit(final ProblemInput input, final File output, final File source) throws IOException { final MultipartContent content = createContent(input, output, source); final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(round.getURL()); urlBuilder.append(DO); final String response = executor.post(urlBuilder.toString(), content); final Gson gson = new Gson(); return gson.fromJson(response, SubmitResponse.class); }