简体   繁体   中英

restlet client side POST request with header and JSON

Could you please comment what wrong with this client side restlet code.

It is necessary:

  1. Add HTTP header X-MF-Auth-Token with value token
  2. Place JSON file to the body of HTTP request
  3. Make POST request to server

Post request generates "400" error. Thank you very much!

        ClientResource cr = new ClientResource(servername + "/json/place");

        cr.getRequest().getAttributes().put("X-MF-Auth-Token", token);

        Form form = new Form ();

        form.add("Category", "");
        form.add("CategoryId", "A1EECAB9-3E66-4F14-92E9-465EDFB22BA7");
        form.add("Latitude", "0");
        form.add("Longitude", "0"); 
        form.add("Name", "Loremipsum");
        form.add("PlaceId", "00000000-0000-0000-0000-000000000099");

    cr.post(form, MediaType.APPLICATION_JSON);

    if (cr.getStatus().isSuccess()) {
        // Register Successful
        Log.v("Register()", "Successeful");
        return true;
    } else {
        Log.v("Register()", "ERROR");
        return false;
    }

    } catch (ResourceException e) {
        // Login Error
    Log.v("AddPlace() error:", e.getStatus().toString());
    return false;
    }

You can use JSONObject instead of Form:

JSONObject jo = new JSONObject();
try {
     jo.add("Category", "");
     jo.add("CategoryId", "A1EECAB9-3E66-4F14-92E9-465EDFB22BA7");
     jo.add("Latitude", "0");
     jo.add("Longitude", "0"); 
     jo.add("Name", "Loremipsum");
     jo.add("PlaceId", "00000000-0000-0000-0000-000000000099");
} catch (JSONException ex) {          
}
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);

i think you're not adding X-MF-Auth-Token to the header.

try

Form headers = (Form) cr.getRequest().getAttributes("org.restlet.http.headers");
if (headers == null) {
    headers = new Form();
    cr.getRequest().getAttributes.put("org.restlet.http.headers", headers);
}
headers.add("X-MF-Auth-Token", token);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM