英文:
How to upload InputStream to HttpURLConnection
问题
I have created a HttpURLConnection using which i need to upload a file to a specific URL. Below is my code
String uURL = "http:some_domain/add";
URL url = new URL(uURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
InputStream iStream = getContent("ABC", "test.json");
Now, i have retrieved my content in iStream
and want to upload it using OutputStreamWriter
. How can i upload the content?
英文:
I have created a HttpURLConnection using which i need to upload a file to a specific URL. Below is my code
String uURL = "http:some_domain/add";
URL url = new URL(uURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
InputStream iStream = getContent("ABC", "test.json");
Now, i have retrieved my content in iStream
and want to upload it using OutputStreamWriter
. How can i upload the content?
答案1
得分: 2
如果您的内容是文本文件,您可以使用OutputStreamWriter。(看起来您的文件是一个json)
try (OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
String data = "{\"name\": \"John\", \"age\": 30}";
osw.write(data);
osw.flush();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw a RuntimeException(e);
}
如果您的内容是二进制文件,您可以使用DataOutputStream
try (OutputStream os = con.getOutputStream();
DataOutputStream dos = new DataOutputStream(os)) {
byte[] data = {0x01, 0x02, 0x03, 0x04, 0x05};
dos.write(data);
dos.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
英文:
If your content is text file you can use OutputStreamWriter. (It's look like your file is a json)
try (OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
String data = "{\"name\": \"John\", \"age\": 30}";
osw.write(data);
osw.flush();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
If your content is binary file you can use DataOutputStream
try (OutputStream os = con.getOutputStream();
DataOutputStream dos = new DataOutputStream(os)) {
byte[] data = {0x01, 0x02, 0x03, 0x04, 0x05};
dos.write(data);
dos.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论