我对PHP、JavaScript和许多其他脚本语言很有经验,但我对Java或Android没有太多经验。

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


当前回答

下面的方法适用于最新的Android库和使用okhttp。

    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormBody.Builder()
            .add("key1", "value1")
            .add("key2", "value2")  //optional
            .add("key3", "value3")  //optional
            .add("key4", "value4")  //optional
            .build();


    Request request = new Request.Builder()
    .url("http://.....")   //URL
    .post(formBody)
    .build();


    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            e.getStackTrace();
        }

        @Override
       public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            if(response.isSuccessful()){
                ResponseBody responseBody = response.body();
                Log.e("TAG_", responseBody.string());
       }
    }

其他回答

下面的方法适用于最新的Android库和使用okhttp。

    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormBody.Builder()
            .add("key1", "value1")
            .add("key2", "value2")  //optional
            .add("key3", "value3")  //optional
            .add("key4", "value4")  //optional
            .build();


    Request request = new Request.Builder()
    .url("http://.....")   //URL
    .post(formBody)
    .build();


    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            e.getStackTrace();
        }

        @Override
       public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            if(response.isSuccessful()){
                ResponseBody responseBody = response.body();
                Log.e("TAG_", responseBody.string());
       }
    }

@primpop的答案,我会添加如何转换字符串中的响应:

HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();

    String result = RestClient.convertStreamToString(instream);
    Log.i("Read from server", result);
}

下面是一个convertStramToString的例子。

注(2020年10月):以下答案中使用的AsyncTask已在Android API级别30中弃用。有关更新的示例,请参考官方文档或本博客文章

更新(2017年6月)答案,适用于Android 6.0+。感谢@Rohit Suthar, @Tamis Bolvari和@sudhiskr的评论。

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

引用:

https://developer.android.com/reference/java/net/HttpURLConnection.html 如何使用NameValuePair使用POST添加参数到HttpURLConnection

原答案(2010年5月)

注意:此解决方案已过时。它只能在5.1版本以下的安卓设备上运行。Android 6.0及以上版本不包括本回答中使用的Apache http客户端。

来自Apache Commons的Http Client是可行的。它已经包含在android中。下面是一个简单的例子,说明如何使用它来执行HTTP Post。

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

您可以使用WebServer类POST一个HttpRequest,并在其侦听器接口中跟踪响应。

WebServer server=new WebServer(getApplicationContext());

server.setOnServerStatusListner(new WebServer.OnServerStatusListner() {
    @Override
    public void onServerResponded(String responce) {

    }

    @Override
    public void onServerRevoked() {

    }
});

现在创建一个DataRack来绑定数据

List<DataRack> racks=new ArrayList<DataRack>();
racks.add(new DataRack("name","Simon"));
racks.add(new DataRack("age","40"));
racks.add(new DataRack("location","Canada"));

现在只需发送带有该机架的POST请求

server.connectWithPOST(MainActivity.this,"http://sangeethnandakumar.esy.es/PROJECTS/PUBLIC_SERVICE/posttest.php",racks);

你需要包括我的库。文件在这里

对我来说,接下来的工作是:

 private sendData() {
     JSONObject jsonObject = new JSONObject();
     jsonObject.accumulate("key1", value1);
     jsonObject.accumulate("key2", value2);

     boolean success = sendPost(SERVER_URL + "/v1/auth", jsonObject);
 }

 private boolean sendPost(String url, JSONObject parameters) {
        boolean requestResult = false;
        InputStream inputStream = null;
        String result = "";
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            json = parameters.toString();

            StringEntity se = new StringEntity(json);
            httpPost.setEntity(se);

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);

            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                requestResult = true;
            } else {
                result = "Did not work!";
                requestResult = false;
            }
            System.out.println(result);
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
            requestResult = false;
        }
        return requestResult;
    }