Android HttpUrlConnection 发送Post请求 PHP页面$_POST接收不到问题

问题描述:
HttpUrlConnection httpUrlConnection = url.openConnection();
1.设置httpUrlConnection .setRequestProperty("Content-Type","application/json");
2.httpUrlConnection 发送Post请求,请求方式如下

DataOutputStream outStream = null;
        final String PARAMETER_SEPARATOR = "&";
        final String NAME_VALUE_SEPARATOR = "=";


        if ((data != null && data.size() != 0)) {
            outStream = new DataOutputStream(httpUrlConnection.getOutputStream());
        } else {
            return;
        }


        if (data != null) {
            // 首先组拼文本类型的参数
            StringBuilder sb = new StringBuilder();
            for (Map.Entry entry : data.entrySet()) {
                sb.append(URLEncoder.encode(entry.getKey(), "utf-8"));
                sb.append(NAME_VALUE_SEPARATOR);
                sb.append(URLEncoder.encode(entry.getValue(), "utf-8"));
                sb.append(PARAMETER_SEPARATOR);
            }
            L.d("postdata merge= " + sb.toString());
            outStream.write(sb.toString().getBytes());
            outStream.flush();
            outStream.close();
        }


3.httpUrlConnection .connect();
4.PHP端采用$_POST方式去获取Post数据
(此处不采用其它方式去获取,例如:file_get_contents("php://input")、GLOBALS['HTTP_RAW_POST_DATA'])“php://input“方式都可以获取到原始数据


结果:取不到Post数据(post数据其实是在httpUrlconnection.getInputStream()是发送到服务器端)
注明:在Servlet端是可以正确获取Post数据,
Servlet这一端用如下实现: 
     InputStream inStream = httpRequest.getInputStream(); 
     ObjectInputStream objInStream = new ObjectInputStream(inStream); 
     Object obj = objInStream.readObject(); 

PHP在取Post数据时是根据相应的Content-Type来获取


解决办法:
在Post请求时去掉Content-Type设置,以默认的内容类型发送 或者设置Content-Type=application/x-www-form-urlencoded


注明:跟connect()放在Post数据之前与之后没有关系,Post数据时会调用getOutputStream(),该方法会打开Http连接,连接打开后,调用connect()会忽略




你可能感兴趣的:(Android知识积累)