dq_1984 2015-09-18 04:33
浏览 44
已采纳

从Android发送变量到PHP服务器

I'm having the hardest time, what I want is for my android application to send a STRING to my server, my server will then choose a function based upon what STRING was sent in PHP. Once the function is done, it will return a JSONObject. I don't want to use any Deprecated methods. I'm trying to implement the sending a STRING to the server to parse and use an appropriate function in PHP then send a JSON back to my android application. Can anyone please show some code from the android side?

So what I'm looking for is, help with the Android code to send a STRING to the server, then read the response from the server which will be a JSON.

  • 写回答

1条回答 默认 最新

  • 我在西湖1 2015-09-18 05:01
    关注

    For Android you can use HTTP Connection URL. An example is mentioned here How to add parameters to HttpURLConnection using POST

    URL url = new URL("http://yoururl.com");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("name", "Chatura"));
    
    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();
    
    conn.connect();
    

    ..

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
    
        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");
    
            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
    
        return result.toString();
    }
    

    For PHP just accept a post request which is coming form Andrid as below

    <?php
    echo '{ "name" = "Hello ' . htmlspecialchars($_POST["name"]) . '"}';
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.