一尘不染

Java 在Android中发送POST数据

java android php

我对PHP,JavaScript和许多其他脚本语言有丰富的经验,但是对Java或Android却没有太多的经验。

我正在寻找一种将POST数据发送到PHP脚本并显示结果的方法。


阅读 295

收藏
2020-02-26

共1个答案

一尘不染

public class CallAPI extends AsyncTask<String, String, String> {

       public CallAPI(){
           //set context variables if required
       }

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
       }

        @Override
        protected String doInBackground(String... params) {
           String urlString = params[0]; // URL to call
           String data = params[1]; //data to post
           OutputStream out = null;

           try {
               URL url = new URL(urlString);
               HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
               out = new BufferedOutputStream(urlConnection.getOutputStream());

               BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
               writer.write(data);
               writer.flush();
               writer.close();
               out.close();

               urlConnection.connect();
           } catch (Exception e) {
               System.out.println(e.getMessage());
           }
       }
   }
2020-02-26