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

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


当前回答

你可以使用URLConnection setDoOutput(true), getOutputStream()(用于发送数据),和getInputStream()(用于接收)。Sun在这方面有一个例子。

其他回答

您可以使用以下方法向URL发送HTTP-POST请求并接收响应。我总是用这个:

try {
    AsyncHttpClient client = new AsyncHttpClient();
    // Http Request Params Object
    RequestParams params = new RequestParams();
    String u = "B2mGaME";
    String au = "gamewrapperB2M";
    // String mob = "880xxxxxxxxxx";
    params.put("usr", u.toString());
    params.put("aut", au.toString());
    params.put("uph", MobileNo.toString());
    //  params.put("uph", mob.toString());
    client.post("http://196.6.13.01:88/ws/game_wrapper_reg_check.php", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            playStatus = response;
            //////Get your Response/////
            Log.i(getClass().getSimpleName(), "Response SP Status. " + playStatus);
        }
        @Override
        public void onFailure(Throwable throwable) {
            super.onFailure(throwable);
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

你还需要在libs文件夹中添加风箱Jar文件

android-async-http-1.3.1.jar

最后,我编辑了你的build.gradle:

dependencies {
    compile files('libs/<android-async-http-1.3.1.jar>')
}

在最后一个重建你的项目。

下面的方法适用于最新的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());
       }
    }

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

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

在新版本的Android中,你必须把所有的web I/O请求放到一个新的线程中。AsyncTask最适合小请求。

@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的例子。