如何使用android studio将Android应用程序的数据发布到服务器上

时间:2016-03-25 02:13:27

标签: android json post server backend

此Android应用正在使用Android Studio。该功能是扫描和显示来自信标/涡流的数据。应用程序已经运行,扫描停止后,数据将保存到本地文件中。但我的问题是当我必须将扫描数据传输到服务器时,我必须将其转发到后端服务器。但我真的不知道什么是最好的方式,因为我是初学者。

以下是数据将传输到本地数据的代码:

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

1 个答案:

答案 0 :(得分:1)

要将数据发送到服务器有很多方法,但我喜欢你使用Volley Library,因为它更快更容易

您可以使用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

我希望这很有帮助,谢谢你