×
您的位置: 首页 > 编程笔记

HttpURLConnection类的调用setRequestProperty功能(setRequestProperty function of HttpURLConnection)

Android 时间:2020-06-15  查看:1496   收藏

I achieve the POST request in Android and upload a picture to service successful.

I did not use the setRequestProperty function; But I want to know what the effect about this function is.

This is the code:

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();

Could anyone explain the effect of setRequestProperty function in HttpURLConnection?

解决方案

Mainly setRequestProperty is used to set below things as per the requirement

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

or

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

Sometimes it become necessary that you have to specify Content-type for the connection.

我实现了Android的POST请求,并上传图片到服务的成功。

我没有使用调用setRequestProperty功能;但我想知道这个功能的影响是什么。

这是code:

 网址URL =新的URL(http://192.168.191.104:8080/myapp/servlet/MyServlet);
HttpURLConnection的连接=((HttpURLConnection类)网址
        .openConnection());
connection.setDoInput(真);
connection.setDoOutput(真);
connection.setUseCaches(假);
connection.setRequestMethod(POST);
connection.connect();
OutputStream的OUT = connection.getOutputStream();
INT LEN;
字节[]缓冲区=新的字节[1024];
//读取文件
的FileInputStream的FileInputStream =新的FileInputStream(环境
        。.getExternalStorageDirectory()getAbsolutePath()+/123.jpg);
而((LEN = fileInputStream.read(缓冲液,0,1024))!=  -  1){
    out.write(缓冲液);
}
了out.flush();
out.close();
fileInputStream.close();
输入的InputStream = connection.getInputStream();
而((LEN = input.read(缓冲液))!=  -  1){
    Log.i(标签,数据:+新的String(缓冲,0,LEN));
}
input.close();
connection.disconnect();

谁能解释HttpURLConnection的?

调用setRequestProperty功能的影响

解决方案

主要调用setRequestProperty用来设置以下事情按要求

  connection.setRequestProperty(连接,保持活动);
connection.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);

  Connection.setRequestProperty(内容类型,text / plain的;字符集= UTF-8);

有时它成为必要的,你必须指定内容类型进行连接。

 

0% (0)
0% (0)