سؤال

I try to login to sugar crm via JSON / REST with the below code:

private String doLogin(String endpointUrl, String username, String password) {
    Map payload = createLoginData(username, password);
    String url = "http://{endpointUrl}";
    URI expanded = new UriTemplate(url).expand(endpointUrl);

    try {
        url = URLDecoder.decode(expanded.toString(), "UTF-8");

    } catch (Exception e) {

        e.printStackTrace();
    }

    String response = template.postForObject(url, payload, String.class);
... }

 private Map createLoginData(String username, String password){

    Map<String, Object> user_auth = new HashMap<String, Object>();
    user_auth.put("user_name", username);
    user_auth.put("password", password);
    Gson gson = new Gson();
    Map<String, Object> input_data = new HashMap<String, Object>();
    Map<String, Object> rest_data = new HashMap<String, Object>();
    rest_data.put("user_auth", user_auth);
    input_data.put("method", "login");
    input_data.put("input_type", "JSON");
    input_data.put("response_type", "JSON");
    input_data.put("rest_data", gson.toJson(rest_data));

return input_data;

}

But instead of a successful logon, the server returns the soruce code of the php-script (the endpoint) as String. Any ideas, what I'm doing wrong?

هل كانت مفيدة؟

المحلول

Following code solved the issue:

HttpEntity request = createLoginRequest(username, password);
String response = template.postForObject(url, request, String.class);

private HttpEntity<MultiValueMap<String, String>> createLoginRequest(String username, String password){
    MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<String, String>();
    requestMap.add("method", "login");
    requestMap.add("input_type", "JSON");
    requestMap.add("response_type", "JSON");
    Map<String, Object> user_auth = new HashMap<String, Object>();
    user_auth.put("user_name", username);
    user_auth.put("password", password);
    Map<String, Object> rest_data = new HashMap<String, Object>();
    rest_data.put("user_auth", user_auth);
    Gson gson = new Gson();
    requestMap.add("rest_data", gson.toJson(rest_data));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(requestMap, headers);
    return request;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top