0

I try post json from Android client to PHP server but failed, server cannot receive any data, I don't see what's wrong with it, so I need help, thanks a lot.

this is Android client kernel code:

String result;
String encoding="UTF-8";
String params="{\"name\":\"123\",\"pass\":\"456\"}";

    try {
        byte[] data=params.getBytes(encoding);
        URL urls=new URL(url);
        HttpURLConnection conn=(HttpURLConnection) urls.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setReadTimeout(4000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        BufferedReader bfread=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str;
        StringBuffer resb=new StringBuffer();
        while ((str=bfread.readLine())!=null)
        {
            resb.append(str);
        }
        result=resb.toString();

and this is server code:

<?php
$data = file_get_contents('php://input'); 
if(empty($data))
{
    echo "no post data";
}
else
{
    print_r($data);
}
?>

android client get the message from server and print on screen, they always show "no post data", obviously client visit server successful, but server not received any data. Then I write a test HTML page to post the data with form, it works. I don't know why.

cycycd
  • 3
  • 5
  • Related: [Sending HTTP POST Request In Java](https://stackoverflow.com/q/3324717/1542723) – Ferrybig Oct 02 '17 at 06:19
  • Have you tried it with the content-type "application/x-www-form-urlencoded"? – xander Oct 02 '17 at 06:25
  • but Android 6.0 is not support HttpClient, they suggested use HttpUrlConnection X( – cycycd Oct 02 '17 at 06:30
  • content type looks wrong, try looking at example here : https://www.androidhive.info/2011/10/android-making-http-requests/ – Pulkit Oct 02 '17 at 06:37
  • @xander still failed X( – cycycd Oct 02 '17 at 06:39
  • @cycycd Try using Volley lib. You can make a request in simple and clear way. And I think `print_r($response)` not a way to response data from the server. Try `echo json_encode($response);` instead. I can write detalied answer if you want it. – phen0menon Dec 31 '17 at 07:23

0 Answers0