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; }
/** * Returns a new instance of {@link LenientTokenResponseException}. * <p> * If there is a JSON error response, it is parsed using * {@link TokenErrorResponse}, which can be inspected using * {@link #getDetails()}. Otherwise, the full response content is read and * included in the exception message. * </p> * * @param jsonFactory JSON factory * @param readResponse an HTTP response that has already been read * @param responseContent the content String of the HTTP response * @return new instance of {@link TokenErrorResponse} */ public static LenientTokenResponseException from(JsonFactory jsonFactory, HttpResponse readResponse, String responseContent) { HttpResponseException.Builder builder = new HttpResponseException.Builder( readResponse.getStatusCode(), readResponse.getStatusMessage(), readResponse.getHeaders()); // details Preconditions.checkNotNull(jsonFactory); TokenErrorResponse details = null; String detailString = null; String contentType = readResponse.getContentType(); try { if (/* !response.isSuccessStatusCode() && */true && contentType != null && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) { details = readResponse .getRequest() .getParser() .parseAndClose(new StringReader(responseContent), TokenErrorResponse.class); detailString = details.toPrettyString(); } else { detailString = responseContent; } } catch (IOException exception) { // it would be bad to throw an exception while throwing an exception exception.printStackTrace(); } // message StringBuilder message = HttpResponseException.computeMessageBuffer(readResponse); if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); return new LenientTokenResponseException(builder, details); }
/** * 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 MultipartFormDataContent() { super(new HttpMediaType("multipart/form-data").setParameter("boundary", "__END_OF_PART__")); }
@Override public MultipartFormDataContent setMediaType(HttpMediaType mediaType) { super.setMediaType(mediaType); return this; }