android - HttpURLConnection 的 setRequestProperty 函数

标签 android post request

我在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/

相关文章:

android - Google Play 专用 channel - 一个 Google 帐户适用于多种设备

Android 尝试将日期与当前日期进行比较,但不起作用

java - (JAVA)向Binance交易所发送http请求错误

ios - 创建 iOS 客户端服务器应用程序。 ASIFormDataRequest 问题

node.js - Azure AMS Node js 应用程序无法建立 TLS 1.2 连接

java - 在一系列小时间范围内处理来自同一客户端的多个请求

android - Flutter:使用不包含 Bloc 类型的上下文调用 blocprovider.of()

android - 在 Kotlin 中,当变量与 lambda 接收器中的字段同名时,如何从作用域函数外部引用变量

ios - 使用 Swift 发布 JSON

javascript - 从 Node.JS 中的两个网站请求 RSS 提要