gpt4 book ai didi

android - HttpURLConnection 的 setRequestProperty 函数

转载 作者:行者123 更新时间:2023-11-30 03:43:42 28 4
gpt4 key购买 nike

我在Android中实现POST请求,上传图片到服务成功。

我没有使用setRequestProperty函数;但是我想知道这个函数的作用是什么。

这是代码:

URL url = new URL("http://192.168.191.104:8080/myapp/servlet/MyServlet");
HttpURLConnection connection = ((HttpURLConnection) url
.openConnection());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.connect();
OutputStream out = connection.getOutputStream();
int len;
byte[] buffer = new byte[1024];
// 读取文件
FileInputStream fileInputStream = new FileInputStream(Environment
.getExternalStorageDirectory().getAbsolutePath() + "/123.jpg");
while ((len = fileInputStream.read(buffer, 0, 1024)) != -1) {
out.write(buffer);
}
out.flush();
out.close();
fileInputStream.close();
InputStream input = connection.getInputStream();
while ((len = input.read(buffer)) != -1) {
Log.i("tag", "data:" + new String(buffer, 0, len));
}
input.close();
connection.disconnect();

谁能解释一下 HttpURLConnection 中 setRequestProperty 函数的作用?

最佳答案

主要是setRequestProperty用来根据需求设置下面的东西

connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

Connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

有时您必须为连接指定 Content-type。

关于android - HttpURLConnection 的 setRequestProperty 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15334920/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com