[英]I can't figure out how to send a file via POST request to https://0x0.st in java
I can't figure out how to send a file via POST request to https://0x0.st in java我不知道如何通过 POST 请求将文件发送到 java 中的https: //0x0.st
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();
There are several Http clients available that you can try.有几个 Http 客户端可供您尝试。 The popular ones would be
最受欢迎的是
key
, client_id
, and direction_id
could be passed as request headers your code could be something like thiskey
、 client_id
和direction_id
可以作为请求标头传递,您的代码可能是这样的byte[] content = readFile() //Read file as bytes here byte[] content = readFile() //这里读取文件为字节
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.这是HttpClient class 的 Javadoc。 The library could be obtained as Maven artifacts or from Github , including source code and Javadoc
该库可以作为Maven 工件或从Github 获得,包括源代码和 Javadoc
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.您上传的密钥必须是file 、 url或short ,否则您将收到 400 bad request响应。 If the request is successful, the provided code returns the URL for your uploaded file.
如果请求成功,则提供的代码会为您上传的文件返回 URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.