如何使用AsyncTask将参数值发送到服务器并获取数据(通过POST请求)?

时间:2019-04-06 06:42:29

标签: java android api http android-asynctask

此代码可以从服务器获取数据,但是如果我的API是POST方法,则如何通过POSt Request将参数传递给服务器并获取数据。代码在这里,请让我知道

    public  class GetTripTeportData extends AsyncTask<String, Integer,String> {
    @Override
    protected void onPreExecute() {...}

    @Override
    protected String doInBackground(String... params) {
        String responseBodyText = null;
        OkHttpClient client = new OkHttpClient();
        try {
            Request request = new Request.Builder().url(excelApi).build();
            Response response = null;
            response = client.newCall(request).execute();//.....

                responseBodyText = response.body().string();
                JSONObject resultData = new JSONObject(responseBodyText);
                JSONArray itemArray = resultData.getJSONArray("data");
                for (int i=0; i<itemArray.length();i++){
                    JSONObject jobject = itemArray.getJSONObject(i);
                    String iduser = jobject.getString("id");
                    String vehicleno = jobject.getString("vehicleno");
                    String startdate = jobject.getString("startdate");
                    allList.add(new ExcelReportAdminResponse(iduser,vehicleno,startdate));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
        return responseBodyText;
    }

    @Override
    protected void onPostExecute(String s) {......}
}

2 个答案:

答案 0 :(得分:0)

要通过具有异步任务的默认http客户端发布数据,您可以执行以下操作:

首先按如下所示创建网络实用程序类:

public class NetworkUtilities {

    public static String postData(String Url, String message ){
        try {
            URL url = new URL(Url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000); /*milliseconds*/
            conn.setConnectTimeout(15000); /* milliseconds */
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setFixedLengthStreamingMode(message.getBytes().length);
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            conn.connect();
            OutputStream os = new BufferedOutputStream(conn.getOutputStream());
            os.write(message.getBytes());
            os.flush();
            InputStream is = conn.getInputStream();
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
        catch (Exception e){
            Log.e("Exception: " , e.toString());
        }
        finally {
            // os.close();
            //is.close();
            //conn.disconnect();
        }
        return "";
    }

}

然后编写异步任务以从NetworkUtilities类中调用该postData()方法,如下所示:

private class PostDataAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return NetworkUtilities.postData(params[0], params[1]);
        }

        @Override
        protected void onPostExecute(String result) {
            Log.e("Data response: ", result);
        }

        @Override
        protected void onPreExecute() {
            // TODO: Loader and stuff to add later here.
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

然后调用该异步任务意味着要调用api,请执行以下操作:

String message = "";
try {
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("user_id", session.getSession());
    message = jsonBody.toString();
} catch (Exception e) {
    Log.e("JSON error: ", e.toString());
}

PostDataAsync postData = new PostDataAsync();
postData.execute("YOUR_POST_API_URL_HERE", message);

通过这种方式,您可以通过异步任务发布数据。

答案 1 :(得分:0)

用于JSON正文的POST呼叫

final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

RequestBody body = RequestBody.create(JSON, /*YOUR JSON REQUEST*/ jsonString);
Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();

try {
   Response response = client.newCall(request).execute();
} catch(IOException io){
  // do something
}