【问题标题】:How to send post request from android to rest api?如何从android发送post请求到rest api?
【发布时间】:2017-08-04 17:13:31
【问题描述】:

我需要在 Spring Boot 中将 json 发送到我的 rest api。 它应该是这样的:

{

    "deviceid":543 ,
    "lat": 56.78,
    "lon": 67.45,
    "date": 1501624800000,
    "time": 18000000
}

我正在使用 google volley。 我在 android 监视器中遇到错误:

[2794] BasicNetwork.performRequest: Unexpected response code 400 for 
http://192.168.0.137:8080/coordinates 

这是 sts-spring 控制台的错误:

 2017-08-03 11:01:21.537  WARN 5056 --- [nio-8080-exec-
 6].w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: 
Could not read document: Unrecognized token 'date': was expecting 
('true','false' or 'null')at [Source:java.io.PushbackInputStream@18362ba; 
line: 1, column: 6]; nested exception is 
com.fasterxml.jackson.core.JsonParseException:  Unrecognized token 
'date': was expecting ('true', 'false' or 'null')at [Source: 
java.io.PushbackInputStream@18362ba; line: 1, column: 6]

这是我的 GPS 服务代码。

public class GPS_Service extends Service {



private LocationListener locationListener;
private LocationManager locationManager;
String insertUrl = "http://192.168.0.137:8080/coordinates";

RequestQueue requestQueue;

String la_string,lo_string;
String deviceid = "987";
String date="1501624800000";
String time ="61200000";



@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public void onCreate() {

    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            Intent i = new Intent("location_update");
            //i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
            //Intent i1 = new Intent("latitude_update");
            //Intent i2 = new Intent("longitude_update");
            i.putExtra("latitude", location.getLatitude());
            i.putExtra("longitude", location.getLongitude());
            sendBroadcast(i);
            la_string=Double.toString(location.getLatitude());
            lo_string=Double.toString(location.getLongitude());





            requestQueue = Volley.newRequestQueue(getApplicationContext());




            StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    System.out.println(response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })

            {

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> parameters  = new HashMap<String, String>();
                    parameters.put("deviceid",deviceid);
                    parameters.put("lat",la_string);
                    parameters.put("lon",lo_string);
                    parameters.put("date","1501624800000");
                    parameters.put("time","18000000");


                    return parameters;
                }


                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> parameters = new HashMap<String, String>();
                    parameters.put("Content-Type", "application/json; charset=utf-8");
                    return parameters;
                }




            };
            requestQueue.add(request);

        }


        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    };

    locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

    //noinspection MissingPermission
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);

}


@Override
public void onDestroy() {
    super.onDestroy();
    if(locationManager != null){
        //noinspection MissingPermission
        locationManager.removeUpdates(locationListener);
    }
}}

正如您看到的日期和时间是硬编码的,我的下一个问题是如何将日期和时间转换为 json 格式?

感谢您的宝贵时间。

【问题讨论】:

标签: android json rest post


【解决方案1】:

我解决了一部分问题,但还有另一部分。 我将数据发送到数据库。 当位置改变时,不是放置一个新的,而是覆盖旧的。 数据库中的 id 字段是自动增量的。 我的帖子请求看起来像。

requestQueue = Volley.newRequestQueue(getApplicationContext());

            Map<String, String> jsonParams = new HashMap<String, String>();

            jsonParams.put("deviceid", "1919");
            jsonParams.put("lat", la_string);
            jsonParams.put("lon", lo_string);
            jsonParams.put("date","1501624800000");
            jsonParams.put("time","18000000");
            JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, insertUrl,
                    new JSONObject(jsonParams),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //   Handle Error
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    headers.put("User-agent", System.getProperty("http.agent"));
                    return headers;
                }
            };
            requestQueue.add(postRequest);

Android 发送 0 作为 id 的值,并覆盖该行。 当我使用 POSTMAN 生成发布请求并且不将 id 字段放入请求数据库中时,会自动增加 id 字段,并放入下一行。 POSTMAN 的发布请求如下所示:

{
    "deviceid":455466 ,
    "lat": 56.78,
    "lon": 67.45,
    "date": 1501624800000,
    "time": 18000000
}

【讨论】:

    猜你喜欢
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2014-11-05
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多