如何使用 android studio 从 android 应用程序 post 数据到服务器

How to post data from android apps using android studio to the server

此 Android 应用正在使用 Android Studio。函数是从beacon/eddystone中扫描并显示数据。该应用程序已经运行,扫描停止后,数据将保存到本地文件。但是我的问题是当我必须将扫描数据传输到服务器时,我必须将它输入到后端服务器。但是我真的不知道什么是最好的方法,因为我是初学者。

这里是数据传输到本地数据的代码:

private void stopScanning(Button scanButton) {
    try {
        beaconManager.stopRangingBeaconsInRegion(region);
    } catch (RemoteException e) {
            // TODO - OK, what now then?
    }
    String scanData = logString.toString();
    if (scanData.length() > 0)
    {
        // Write file
        fileHelper.createFile(scanData);
        // Display file created message.
        Toast.makeText(getBaseContext(),
                "File saved to:" + getFilesDir().getAbsolutePath(),
                Toast.LENGTH_SHORT).show();
        scanButton.setText(MODE_STOPPED);
    } else {
        // We didn't get any data, so there's no point writing an empty file.
        Toast.makeText(getBaseContext(),
                "No data captured during scan, output file will not be created.",
                Toast.LENGTH_SHORT).show();
        scanButton.setText(MODE_STOPPED);
    }
}

向服务器发送数据有很多方法,但我更喜欢使用 Volley 库,因为它更快更容易

您可以使用 volley 来获取和发送数据,例如:

   //Request serever for JsonObject
  JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            //Your code to proceed with fetched data

          }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
              //This is the method used to put params into the body, this what you will have to use for sending post data
        @Override
        public Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();

              params.put("name","jois");
            return params;
        }

    };

    Volley.newRequestQueue(getApplicationContext()).add(request);




compile 'com.mcxiaoke.volley:library:1.0.19' This is the dependice you will have to add in build.gradle file to use volley library

希望对您有所帮助,谢谢