我在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函数的效果吗?
答案 0 :(得分:1)
主要是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。
答案 1 :(得分:0)
设置指定的请求标头字段的值。该值仅由当前URLConnection实例使用。只能在建立连接之前调用此方法。