Java编程Post数据请求和接收代码详解

时间:2022-06-12 23:14:13

这两天在做http服务端请求操作,客户端post数据到服务端后,服务端通过request.getParameter()进行请求,无法读取到数据,搜索了一下发现是因为设置为text/plain模式才导致读取不到数据

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

若设置为以下方式,则通过request.getParameter()可以读取到数据

?
1
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

enctype的三种编码

form表单中enctype属性可以用来控制对表单数据的发送前的如何进行编码,即在发送到服务器之前,所有字符都会进行编码(空格转换为"+"加号,特殊符号转换为ASCIIHEX值)。默认是application/x-www-form-urlencoded。

multipart/form-data用于发送二进制的文件,其他两种类型不能用于发送文件

text/plain用于发送纯文本内容,不对特殊字符进行编码,一般用于email之类的。

application/x-www-form-urlencoded和text/plain的区别简单讲就是一个发送html内容,一个发送纯文本内容

application/x-www-form-urlencoded在发送前编码所有字符(默认)

multipart/form-data不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。

text/plain空格转换为"+"加号,但不对特殊字符编码。

当定义enctype为application/x-www-form-urlencoded时,使用以下方式接收数据

?
1
request.getParameter(参数名);

当定义enctype为text/plain时,使用以下方式接收数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
    // 接收请求数据
    BufferedReader reader = request.getReader();
    char[] buf = new char[512];
    int len = 0;
    StringBuffer contentBuffer = new StringBuffer();
    while ((len = reader.read(buf)) != -1) {
      contentBuffer.append(buf, 0, len);
    }
        String content = contentBuffer.toString();
        
        if(content == null){
            content = "";
        }

post与get

tp请求在所有的编程语言中几乎都是支持的,我们常用的两种为:GET,POST请求。一般情况下,发送一个GET请求都很简单,因为参数直接放在请求的URL上,对于POST请求,由于其数据是在消息体中发送出去的,所以相对来说要麻烦一点,再涉及到需要发送文件等二进制的数据类型,就更需要更多的处理。

post和get可以通过键值对的方式进行参数传输,服务端通过request.getparameter方式进行请求获取数据。

客户端post数据到服务端,服务端接收处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
public class UrlConnection {
    @SuppressWarnings("finally")
      public static Boolean response(String url,String content) {
        String line     = "";
        String message    = "";
        String returnData  = "";
        Boolean postState   = false;
        BufferedReader bufferedReader = null;
        try {
            URL urlObject = new URL(url);
            HttpURLConnection urlConn = (HttpURLConnection) urlObject.openConnection();
            urlConn.setDoOutput(true);
            /*设定禁用缓存*/
            urlConn.setRequestProperty("Pragma:", "no-cache");
            urlConn.setRequestProperty("Cache-Control", "no-cache");
            /*维持长连接*/
            urlConn.setRequestProperty("Connection", "Keep-Alive");
            /*设置字符集*/
            urlConn.setRequestProperty("Charset", "UTF-8");
            /*设定输出格式为json*/
            urlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            /*设置使用POST的方式发送*/
            urlConn.setRequestMethod("POST");
            /*设置不使用缓存*/
            urlConn.setUseCaches(false);
            /*设置容许输出*/
            urlConn.setDoOutput(true);
            /*设置容许输入*/
            urlConn.setDoInput(true);
            urlConn.connect();
            OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConn.getOutputStream(),"UTF-8");
            outStreamWriter.write(content);
            outStreamWriter.flush();
            outStreamWriter.close();
            /*若post失败*/
            if((urlConn.getResponseCode() != 200)){
                returnData = "{\"jsonStrStatus\":0,\"processResults\":[]}";
                message = "发送POST失败!"+ "code="+urlConn.getResponseCode() + "," + "失败消息:"+ urlConn.getResponseMessage();
                // 定义BufferedReader输入流来读取URL的响应
                InputStream errorStream = urlConn.getErrorStream();
                if(errorStream != null)
                        {
                    InputStreamReader inputStreamReader = new InputStreamReader(errorStream,"utf-8");
                    bufferedReader = new BufferedReader(inputStreamReader);
                    while ((line = bufferedReader.readLine()) != null) {
                        message += line;
                    }
                    inputStreamReader.close();
                }
                errorStream.close();
                System.out.println("发送失败!错误信息为:"+message);
            } else{
                /*发送成功返回发送成功状态*/
                postState = true;
                // 定义BufferedReader输入流来读取URL的响应
                InputStream inputStream = urlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                while ((line = bufferedReader.readLine()) != null) {
                    message += line;
                }
                returnData = message;
                inputStream.close();
                inputStreamReader.close();
                System.out.println("发送POST成功!返回内容为:" + message);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
            return postState;
        }
    }
    /*读取request数据*/
    public static String getRequestData(HttpServletRequest request) throws IOException{
        BufferedReader reader = request.getReader();
        char[] buf = new char[512];
        int len = 0;
        StringBuffer contentBuffer = new StringBuffer();
        while ((len = reader.read(buf)) != -1) {
            contentBuffer.append(buf, 0, len);
        }
        String content = contentBuffer.toString();
        if(content == null){
            content = "";
        }
        return content;
    }
}

总结

以上就是本文关于Java编程Post数据请求和接收代码详解的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。

原文链接:http://blog.csdn.net/zouqingfang/article/details/44781909