dongzun9958 2015-12-26 07:52
浏览 319

使用HttpURlConnection POST POST json数据

I am trying to send json data to server using HTTPURLConnection. But every time response id null from server. i tried by POSter also but it is working there.

 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;
}

Keeping my json string in "data" key

PHP:-

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

       // php code.....

   } else {

       // control comes here.. 

       // php code.....
   }

Here $_POST['data'] is not working. Please check whats wrong in PHP or Andooid code.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
    • ¥88 实在没有想法,需要个思路
    • ¥15 MATLAB报错输入参数太多
    • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
    • ¥15 有赏,i卡绘世画不出
    • ¥15 如何用stata画出文献中常见的安慰剂检验图
    • ¥15 c语言链表结构体数据插入
    • ¥40 使用MATLAB解答线性代数问题
    • ¥15 COCOS的问题COCOS的问题
    • ¥15 FPGA-SRIO初始化失败