I can't figure out how to send a file via POST request to https://0x0.st in java
My code:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("key", key);
builder.addTextBody("client_id", client_id );
builder.addTextBody("direction_id", direction_id);
ContentType fileContentType = ContentType.create("image/jpeg");
String fileName = file.getName();
builder.addBinaryBody("client_files", file, fileContentType, fileName);
HttpEntity entity = builder.build();
CodePudding user response:
There are several Http clients available that you can try. The popular ones would be
- Apache Http client
- OK Http client.
I actually wrote my own Http client which is part of MgntUtils Open Source library written and maintained by me. The reason I wrote my own Http client is to provide a very simple option. It doesn't support all the features provided in other clients but is very simple in use, and it does support uploading and downloading binary information. Assuming from your code that
key
,client_id
, anddirection_id
could be passed as request headers your code could be something like this
byte[] content = readFile() //Read file as bytes here
byte[] content = readFile() //Read file as bytes hereHttpClient client = new HttpClient();
client.setContentType("image/jpeg");
client.setRequestHeader("key", key);
client.setRequestHeader("client_id", client_id);
client.setRequestHeader("direction_id", direction_id);
String result = client.sendHttpRequest(" https://0x0.st", HttpMethod.POST, ByteBuffer.wrap(content));
System.out.println("Upload result: " result); //If you expect any textual reply
System.out.println("Upload HTTP response" client.getLastResponseCode() " " client.getLastResponseMessage());
Here is Javadoc for HttpClient class. The library could be obtained as Maven artifacts or from Github, including source code and Javadoc
CodePudding user response:
Try this:
public static String uploadFile(String path, ContentType contentType) throws IOException {
File file = new File(path);
URI serverURL = URI.create("https://0x0.st/");
try(CloseableHttpClient client = HttpClientBuilder.create().build()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file, contentType, file.getName());
HttpEntity requestEntity = builder.build();
HttpPost post = new HttpPost(serverURL);
post.setEntity(requestEntity);
try(CloseableHttpResponse response = client.execute(post)) {
HttpEntity responseEntity = response.getEntity();
int responseCode = response.getStatusLine().getStatusCode();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
if(responseCode == 200)
return responseString;
else throw new RuntimeException(responseCode ": " responseString);
}
}
}
The key for your upload must be file, url or shorten, otherwise you will get a 400 bad request response. If the request is successful, the provided code returns the URL for your uploaded file.