Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Unable to Commit file on Bitbucket cloud using REST API in Java code.

prajakta101 July 8, 2019

Hi Team,

I want to commit text file "demo2.txt" to bitbucket server using rest API.

I can upload the same file using CURL request on Postman but it's not working with Java code.

As shown in the below code I want to send string object "str" as the body. After executing this code I am getting 201 as response status code means "created" but file is not uploaded on bitbucket server.

Please let me know if there is any other way to do this.
--------------------------------------------------------------------------------

URL url = new URL("https://api.bitbucket.org/2.0/repositories/{team name}/
{repository name}/src");

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

httpCon.setRequestProperty("X-Requested-with", "Curl"); 
httpCon.setDoOutput(true);
httpCon.setDoInput(true); 
httpCon.setRequestProperty("Connection", "Keep-Alive");
httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
httpCon.setRequestProperty("Accept", "application/x-www-form-urlencoded");
httpCon.setRequestProperty("Authorization", basicauth); 
httpCon.setRequestMethod("POST");

String str =
"{" + "\"-F\":\"File3=@/D:/log/demo2.txt\" " + "}";

try
{ OutputStream output = httpCon.getOutputStream(); output.write(str.getBytes()); output.close(); 
}
catch(Exception e){
System.out.println(e.getMessage()); }
int responseCode = httpCon.getResponseCode();
String inputLine; 
StringBuffer response = new StringBuffer();

if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
while ((inputLine = in.readLine()) != null)

{ 
response.append(inputLine);
}

in.close();
List<String> message = new ArrayList<>();
message.add(response.toString()); 
}

1 answer

0 votes
Daniil Penkin
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
July 8, 2019

Hello @prajakta101,

So in your code you specify content type of your request as multipart/form-data which means that payload should be encoded accordingly, see second example here, for instance.

However, for a simple file content like you have in your code excerpt it is probably easier to use application/x-www-form-urlencoded content type — in that case all payload should be simply encoded into URL (with proper escaping).

The value your provided in Accept header doesn't make sense here as Bitbucket will never return URL encoded form as a response to your request.

Hope this helps.

Cheers,
Daniil

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events