`

PHP JAVA关于post请求数据接收的处理

阅读更多

PHP接收post请求数据主要采用两种方式:

     1、$_POST[index]方式

     2、$data = file_get_contents("php://input");

 

     Content-Type仅在取值为application/x-www-data-urlencoded和multipart/form-data两种情况下,PHP才会将http请求数据包中相应的数据填入全局变量$_POST。因此,如果使用$_POST来获取post过来的数据时,需要注意Content-Type类型,如果不是application/x-www-data-urlencoded和multipart/form-data,则采用file_get_contents("php://input");进行获取。

 

     php://input 可以读取http entity body中指定长度的值,由Content-Length指定长度,不管是POST方式或者GET方法提交过来的数据。但是,一般GET方法提交数据 时,http request entity body部分都为空。

 

    例如在传递json串的时候,通过file_get_contents("php://input");获取原始串,然后通过json_decode()进行解析。

 

Java的servlet中接收Post请求数据主要采用两种方式:

    1、request.getParameter()

    2、request.getInputStream();

 

    Content-Type仅在取值为application/x-www-data-urlencoded和multipart/form-data两种情况下,request.getParameter()才能获取到值,否则返回空。

    Content-Type为其他类型时,可以采用如下方式进行获取:

 

String json = org.apache.commons.io.IOUtils.toString(request.getInputStream());
System.out.println(json);

 之后对取到的值(字符串)进行处理。

 

 

因此,通过HttpClient4.5.2的fluent api发送post请求时,接收方对应的处理方式如下:

 

---------------------方式一:
发送方:
Request.Post(url).bodyForm(Form.form().add("loginName", "vip").add("password", "secret").build()).execute().handleResponse(myRespHandler);
接受方:
java:request.getParameter() 或 request.getInputStream()
php:$_POST  或  file_get_contents('php://input');
---------------------方式二:
发送方:
Request.Post(url).bodyString(req, ContentType.APPLICATION_JSON).execute().handleResponse(myRespHandler);
接收方:
java:request.getInputStream()
      String json = org.apache.commons.io.IOUtils.toString(request.getInputStream());
php:  file_get_contents("php://input");

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics