Upload file using REST API

Hi everyone!

I’ve searched for this issue on the community and seems to be discussed a couple of times but with no real resolution.

I’m trying to upload an XML file using a POST request and form-data, but I get the following error response:

  "error":"The results file is required."

If I use curl it works fine. Also works fine with Postman.
My real intention is to create the request manually (using a script and withMultipartFormDataBodyContent()) but first I wanted to make sure it works using ObjectRepository.

Can someone please help me with this?


1 Like

After a looooooooooooong time of searching and trying different things I already found the solution (that works for me). It uses Okhttp library so you will need to import it.
If anyone else need it, there it is:

	public void importJUnitTestExecRequest() {
		OkHttpClient client = new OkHttpClient();
		String reportFolder = GlobalVariable.reportFolder + "\\JUnit_Report.xml";
		File file = new File(reportFolder);

		String url = GlobalVariable.importTestExecJUnitEndpoint+"?testExecKey="+GlobalVariable.testExecKey;

		//Form request body that will be a multipart
		RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
				.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("text/xml"), file))

		//Form the actual request adding necessary headers
		Request request = new Request.Builder()
				.addHeader("Content-Type", GlobalVariable.contentTypeMultipart)

		Response response = null;

		try {
			response = client.newCall(request).execute();
			println("************ IMPORT TEST EXECUTION RESULTS RAW RESPONSE ************");
			println("Response status: " + response);
			if (response.isSuccessful()){
				String responseBody = response.body().string();
				println("************ IMPORT TEST EXECUTION RESULTS RESPONSE BODY ************");
			} else {
				throw new IOException("Unexpected HTTP code " + response);
		} catch (IOException e) {


You are welcome.


this is not a folder, but a file :stuck_out_tongue:
LE: sorry but i cannot hold it due to work habits, i am paranoid at code review

Uhg that’s true.
Probably I copied&pasted the name, that’s beacuse :sweat_smile:

Changed it, thanks!


Can you(susana.maria.repeto) please explain what is under your GlobalVariable.contentTypeMultipart? No matter what I have tried, this code doesn’t work for me.

Please advise

I applied this one and can upload file successfully:
def requestObject = builder
new TestObjectProperty(“Content-Type”, ConditionType.EQUALS, “multipart/form-data”),
new TestObjectProperty(“accept”, ConditionType.EQUALS, “/”),
new TestObjectProperty(“Authorization”, ConditionType.EQUALS, “Bearer ${token}”)
new FormDataBodyParameter(“file”, file.toString(), FormDataBodyParameter.PARAM_TYPE_FILE)

	def response = WS.sendRequest(requestObject)