How to configure and send multipart request via RestAssured - java

I'm trying to configure and send a multipart request like the following one:
------boundary
Content-Disposition: form-data; name="before"; filename="blob"
Content-Type: application/vnd...+json;type=some_type
{some JSON}
------boundary
Content-Disposition: form-data; name="after"; filename="blob"
Content-Type: application/vnd...+json;type=some_type
{another JSON}
------boundary--
So I tried to configure a request, as in the code below
RestAssuredConfig config = RestAssured.config().multiPartConfig(
new MultiPartConfig().defaultCharset(StandardCharsets.UTF_8).
defaultBoundary("--boundary--"));
MultiPartSpecification m1 new MultiPartSpecBuilder(
new ObjectMapper().writeValueAsString(some_JSON_transformed_to_HashMap)).
fileName("blob").controlName("before").
mimeType(ContentType.TEXT.getAcceptHeader()).
header("ContentType", "application/vnd...+json;type=some_type").build();
MultiPartSpecification m2 = new MultiPartSpecBuilder(
new ObjectMapper().writeValueAsString(another_JSON_transformed_to_HashMap)).
fileName("blob").controlName("after").
mimeType(ContentType.TEXT.getAcceptHeader()).
header("ContentType", "application/vnd...+json;type=some_type").build();
RequestSpecification request = RestAssured.given().multiPart(m1).multiPart(m2).
config(config).
.header("Content-Type", "multipart/form-data; boundary=" + config.getMultiPartConfig().defaultBoundary());
request.post("some_url");
But when I try to execute it, server says that resource is invalid, but I believe, that JSONs is correct, so I suppose my multipart configuration is incorrect. How should I configure a request?

You could try something similar to below code .
given().auth().preemptive()
.basic("Jirausername", "Jirapassword")
.header("X-Atlassian-Token", "nocheck")
.multiPart(new File("/home/users/cat.log"))
.when().post("http://localhost:8181/rest/api/2/issue/STS-223/attachments");

Related

How to send a POST with form-data in Body in RestAssured setting multipart with a specific content-type

Trying to send a POST request with form-data in Body in RestAssured, however not sure how should do it.
In Postman, it's fine.
I've tried things like:
public Response create() {
return super
.given()
.contentType("multipart/form-data")
.multiPart("MetaDataOne", new File("file.txt"))
.multiPart("MetaDataTwo", new File("file2.txt"))
.basePath("/create")
.log().all()
.post()
.then()
.log().all()
.extract()
.response();
}
But seems that my files are not being sent in the request.
Console log
Multiparts
Content-Disposition form-data; name = MetadataOne; filename = file
Content-Type: application/octet-stream
{"error": 415, "description": Content type application/octet-stream not supported}
Headers
Can you try with this, This should overwrite the Content-Type as multipart/form-data rather than application/octet-stream
given().contentType("multipart/form-data").multiPart("MetaDataOne", new File("file.txt"), "multipart/form-data")
.multiPart("MetaDataTwo", new File("file2.txt"), "multipart/form-data").basePath("/create").log().all()
.post().then().log().all().extract().response();
It's very simple to consume a RESTFull webservice Api, just follow these simple steps
Step 1: Create a Request Object pointing to the Service
RestAssured.baseURI ="https://myhost.com/xyz";
RequestSpecification request = RestAssured.given();
Step 2: Create a JSON object which contains all the form fields
JSONObject jsonObject = new JSONObject();
jsonObject.put("Form_Field_1", "Input Value 1");
jsonObject.put("Form_Field_2", "Input Value 2");
jsonObject.put("Form_Field_3", "Input Value 3");
jsonObject.put("Form_Field_4", "Input Value 4");
Step 3: Add JSON object in the request body and send the Request
request.header("Content-Type", "application/json");
request.body(jsonObject.toJSONString());
Post the request and check the response
Response response = request.post("/register");
Step 4: Validate the Response
int statusCode = response.getStatusCode();

Got 404 when posting attachment to confluence with Java and Apache HttpClient

I am trying to post images to an confluence page as attachment to a content.
Here is the function of my java application:
public void postAttachment(File f, String comment) throws IOException {
if (!f.exists() || !f.canRead()) {
throw new IOException("Could not access file " + f.getAbsolutePath());
}
final FileBody bin = new FileBody(f);
final StringBody cmt = new StringBody(comment, ContentType.TEXT_PLAIN);
final HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", cmt).build();
final HttpPost post = new HttpPost(baseUrl + "/rest/api/content/" + contentid + "/child/attachment");
post.setEntity(reqEntity);
post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(props.getString("confluence_user"),props.getString("confluence_password")), "UTF-8", false));
post.addHeader("X-Atlassian-Token:","no-check");
System.out.println("executing request " + post.getRequestLine());
final CloseableHttpClient httpclient = HttpClients.createDefault();
final CloseableHttpResponse response = httpclient.execute(post);
System.out.println(post.getRequestLine());
System.out.println(response.toString());
if (response.getStatusLine().getStatusCode() == 404) {
throw new IOException("Status 404 thrown!");
}
}
The output in the terminal is:
POST https://xxx.xxxx.de:443/rest/api/content/38262140/child/attachment
and then
HttpResponseProxy{HTTP/1.1 404 Not Found [Server: Apache-Coyote/1.1, X-ASEN: SEN-1343236, Set-Cookie: JSESSIONID=9DF46011711C2828977E17A945D023E1; Path=/; Secure; HttpOnly, X-Seraph-LoginReason: OK, X-AUSERNAME: xxxx, X-Content-Type-Options: nosniff, Content-Type: text/plain, Transfer-Encoding: chunked, Date: Tue, 27 Sep 2016 11:20:35 GMT] ResponseEntityProxy{[Content-Type: text/plain,Chunked: true]}}
(I changed the domain name and username just for this post..)
So all seems ok. If i copy the generated POST url and do a GET in the browser i get a json snippet with an attachment list, manually uploaded before. So the POST url should be ok.
I searched across the web but i cant find where i am wrong with my code.. Any Suggestions?
Confluence is strict in "X-Atlassian-Token" header value. You have extra : in header name.
Change
post.addHeader("X-Atlassian-Token:","no-check");
to
post.addHeader("X-Atlassian-Token","no-check");
This will create correct header, and 404 error will go away
I too am presently struggling to add attachments; now on to a 403 Forbidden...
I worked through my 404 finding that it was in my (bad) URL. However, your URL does appear correct. Any chance that Page ID is off or your authenticated user lacks permissions (globally, in the space, or at the page level)?
Edit: Oh! And, as mtheriault's post suggests, check the attachment size vis a vis your Confluence instance's "attachmentMaxSize".

MultipartEntityBuilder HttpPost socket write error in java

I am trying file upload with httpPost request (by MultipartEntityBuilder) in java. But i get a Software caused connection abort: socket write error.
Here is my httpPost body (in wireShark)
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="csrf_token"
csrf:sjwzV6dOZaNFwc0jWVrNNcFvhM7uv3BK00vZ0hCgEUzi2cG7r7Arx0Q3UZKlXeaR
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="imagefilename"; filename="myfile.bin"
Content-Type: application/octet-stream
²qz‹ÁOOõMÓâg‘Ç`:----This area is file's binary code------Êëá‡/oåup
code side is:
File file = new File(filePath);
String message = csrf_token;
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("imagefilename", file, ContentType.DEFAULT_BINARY, file.getName());
builder.addTextBody("csrf_token", message, ContentType.DEFAULT_BINARY);
//
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
and error:
Is there any idea? thanks for all.
i resolved the problem, thesee links are useful for answer
here is fileupload with http Client example
here is fileupload too, with httpUrlConnection

how to send and accept file over Java Http Post?

I just want to send a text file and a JPEG file over the network. fortunately, i have access to both the server code and the client code. Here's my (google app engine) code.
private void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
GcsFilename filename = new GcsFilename("my-bucket", "my-file");
Builder fileOptionsBuilder = new GcsFileOptions.Builder();
fileOptionsBuilder.mimeType("text/html");
GcsFileOptions fileOptions = fileOptionsBuilder.build();
GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, fileOptions);
byte[] buffer = new byte[1024];
InputStream reader = req.getInputStream();
BufferedOutputStream outStream = new BufferedOutputStream(Channels.newOutputStream(outputChannel));
while(true) {
int bytesRead = reader.read(buffer);
if (bytesRead == -1) {
break; // have a break up with the loop.
} else if (bytesRead < 1024) {
byte[] temp = Arrays.copyOf(buffer, bytesRead);
outStream.write(temp);
} else {
outStream.write(buffer);
}
}
outStream.close();
outputChannel.close();
}
As you can see, i use a raw InputStream to get all the data that is sent over the net.
and on the client side, i send a text file over like so: (in Android)
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://my-hosted-url/postit");
MultipartEntity entity = new entity.addPart("myImageFile", new FileBody(someLogFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpClient.execute(httpost);
This works just fine... sort of. the problem is that when i try to view the file/data that is sent, it has a header on top of it, as such:
--NNqarc4FsG0G8hUzd82A6TCjgzKH Content-Disposition: form-data; name="myString" Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 8bit STRING_VALUE ---NNqarc4FsG0G8hUzd82A6TCjgzKH Content-Disposition: form-data; name="myImageFile"; filename="something.txt" Content-Type: application/octet-stream Content-Transfer-Encoding: binary
[Thu Aug 14 17:14:26 PDT 2014] then the real log starts here...
How do i get rid of the headers that is somehow stuck to the body?
What you have here is a multipart request. It is a single request where the body consists of the various parts separated by a separator string.
In your case, it's more easily viewed as:
--NNqarc4FsG0G8hUzd82A6TCjgzKH
Content-Disposition: form-data; name="myString"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit
STRING_VALUE
---NNqarc4FsG0G8hUzd82A6TCjgzKH
Content-Disposition: form-data; name="myImageFile"; filename="something.txt"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
[binary here]
It has two parts where each part has its corresponding headers and body. I'm guessing you're interested in the bodies. You'll need to extract them.
You can either read the HTTP specification and/or the specification about multipart requests and write your own parser, or you can use some built-in (I don't know if GAE is Servlet 3.0 ready or not) or 3rd party methods. See these
How can my Servlet receive parameters from a multipart/form-data form?
Convenient way to parse incoming multipart/form-data parameters in a Servlet
How can I handle multipart/form-data POST requests in my java servlet?

how to Upload files using MULTIPART file upload in DROPBOX

I am trying to upload files using MULTIPART entity method.But it fails in error says that {"error": "file parameter value 'None' is invalid"}
My code is:
File file = new File("C:/Users/sst-06/Desktop/new.txt");
service.signRequest(dropBoxToken, request);
HttpClient client = new DefaultHttpClient();
String url="https://api-content.dropbox.com/1/files/dropbox/test";
System.out.println("URL "+url);
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity( );
FileBody fileBody= new FileBody( file,"application/x-unknown");
entity.addPart( "file",fileBody);
System.out.println(fileBody);
for (String key : request.getHeaders().keySet()){
post.setHeader(key, request.getHeaders().get(key));
}
post.setEntity( entity );
String response = EntityUtils.toString( client.execute(post).getEntity(), "UTF-8" );
client.getConnectionManager().shutdown();
System.out.println(response);
And my entity file contains all the parameters as mentioned.
--hkYO-pBlK0UQLXjtVKLrBkOSXz7mYe-8WBVBvAnX
Content-Disposition: form-data; name="file"; filename="new.txt"
Content-Type: application/x-unknown
Content-Transfer-Encoding: binary
--File contents--
--hkYO-pBlK0UQLXjtVKLrBkOSXz7mYe-8WBVBvAnX--
I dont know where i felt with error.Please help.
Thanks in advance
Is there any reason why you want to use the web service directly? Will you consider using the DropBox Java SDK?
https://www.dropbox.com/static/developers/dropbox-java-sdk-1.5.3.zip

Categories

Resources