Search code examples
javadynamics-crm

400 status code when using $filter parameter in java request to dynamics crm


I'm trying query data from dynamics CRM through java HttpUrlConnection object. I always get an HTTP 400 status code when my request include the $filter parameter. But when I remove this parameter my request works fine. I have tried my request directly on a browser and it works fine too. The code below shows how I built my request

public String getContactByPhoneNumber(String phoneNumber) throws Exception {
    HttpURLConnection connection = null;
    URL url = new URL(completeURL + "/contacts?select=lastname&$filter=telephone1 eq '"+phoneNumber+"'");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("OData-MaxVersion", "4.0");
    connection.setRequestProperty("OData-Version", "4.0");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Prefer", "odata.include-annotations=\"*\"");
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.addRequestProperty("Authorization", "Bearer " + token);
    if (connection.getResponseCode() == 200) {
        String response = getResponseAsString(connection);
        return response;
    } else {
        String error = getErrorAsString(connection);
        System.err.println(error);
        return null;
    }

}

Did anyone met this error? How can I solve it?


Solution

  • I haven't tested this myself, so I can't guarantee that it works, but you could try URL-encoding the $filter parameter name and its value:

    import java.net.URLEncoder;
    
    // ... 
    
      URL url = new URL(
        completeURL + "/contacts?select=lastname&"
        + URLEncoder.encode("$filter", "UTF-8") + "="
        + URLEncoder.encode("telephone1 eq '"+phoneNumber+"'", "UTF-8"));