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

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


当前回答

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

其他回答

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

下面是一个完整的解决方案,它运行在后台线程中,向Web API发送一个HTTPS POST多部分请求。实际测试和工作代码。注意:“\n”字符需要在顶部的“最终字符串”中进行正确的请求格式化。

我有困难要么理解,转换,或完成以上解决方案,我的多部分POST需求。

    @Override
    protected Integer doInBackground(String... files) {

        final String MULTIPART_BOUNDARY = "xxYYzzSEPARATORzzYYxx";
        final String MULTIPART_SEPARATOR = "--" + MULTIPART_BOUNDARY + "\n";
        final String MULTIPART_FORM_DATA = "Content-Disposition: form-data; name=\"%s\"\n\n";
        final String FORM_DATA_FILE1 = "file1";
        final String FORM_DATA_FILE2 = "file2";

        OutputStream outputStream;
        Integer responseCode = 0;
        try {
            URL url = new URL("https://www.example.com/api/endpoint?n1=v1&n2=v2");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + MULTIPART_BOUNDARY);
            urlConnection.setConnectTimeout(6000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            writer.write(MULTIPART_SEPARATOR);
            writer.write(String.format(MULTIPART_FORM_DATA, FORM_DATA_FILE1));
            writer.write(files[0]);
            writer.write(MULTIPART_SEPARATOR);
            writer.write(String.format(MULTIPART_FORM_DATA, FORM_DATA_FILE2));
            writer.write(files[1]);
            writer.write(MULTIPART_SEPARATOR);
            writer.flush();
            writer.close();
            outputStream.close();
            urlConnection.connect();
            responseCode = urlConnection.getResponseCode();
            Log.d("ResponseCode:", String.valueOf(responseCode));
            urlConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseCode;
    }

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

 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库和使用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());
       }
    }

最好使用Apache Commons HttpClient,它已经包含在android中了。 看一看 Android开发人员:Apache HTTP客户端包摘要 一般API信息。