使用HttpURlConnection POST POST json数据

时间:2015-12-26 07:52:04

标签: php android json httpurlconnection

我正在尝试使用HTTPURLConnection将json数据发送到服务器。但是每次响应都是来自服务器的null。我也尝试过POSter,但它正在那里工作。

 try {
        jsondata ="{\"A\":\"1234\",\"country_code\":\"91\",\"name\":\"sajal\",\"phone_number\":\"88999\"}";
        URL url = new URL(uri);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setConnectTimeout(3000);
        httpConn.setDoInput(true);  
        httpConn.setDoOutput(true);  
        httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        httpConn.setRequestMethod("POST");

        StringBuffer requestParams = new StringBuffer();

        if (jsondata != null && jsondata.length() > 0) {
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("data", jsondata);
            String query = builder.build().getEncodedQuery();

            OutputStream os = httpConn.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));


            bufferedWriter.write(query);
            bufferedWriter.flush();
            bufferedWriter.close();
            os.close();
        }

        InputStream inputStream = null;
        if (httpConn != null) {
            inputStream = httpConn.getInputStream();
        } else {
            throw new IOException("Connection is not established.");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        response = reader.readLine();
        reader.close();

        if (httpConn != null)
            httpConn.disconnect();


    } catch (UnknownHostException one) {
        return response;

    } catch (SocketException two) {
         return response;

    } catch (Exception three) {
         return response;
}


    return response;
}

将我的json字符串保存在“data”键中

PHP: -

  if (isset($_POST['data'])) {
       $data = json_decode($_POST["data"], true);

       // php code.....

   } else {

       // control comes here.. 

       // php code.....
   }

这里$ _POST ['data']不起作用。请检查PHP或Andooid代码中的错误。

0 个答案:

没有答案