409 HTTP ERROR when trying to send a JSON string i

2019-08-02 11:53发布

I need to make an HTTP POST sending a JSON string in body request, in the simplest way possible. The api is this: 'api.nimble.com/api/v1/contact' (https://nimble.readthedocs.org/en/latest/contacts/basic/create/).

The JSON is a String variable (not necessary to use any additional libraries), should be sent in the body of the request.

I have the following Java code but always return 409 HTTP ERROR.

Someone could tell me what I should change/add in the code to work correctly? Thanks a lot!

UPDATE: Solution is validate with: http://jsonlint.com/ . The correct JSON string is (escape double quote and remove commas to the end of the fields):

String str_JSON="{\"fields\": {\"first name\": [{\"value\": \"Jack\",\"modifier\": \"\"}],\"last name\": [{\"value\": \"Daniels\",\"modifier\": \"\"}],\"phone\": [{\"modifier\": \"work\",\"value\": \"123123123\"},{\"modifier\": \"work\",\"value\": \"2222\"}]},\"type\": \"person\",\"tags\": \"test\"}";

Code:

String str_response="";
String access_token=request.getParameter("at");
String data="{'fields': {'first name': [{'value': 'Jack','modifier': '',}],'last name': [{'value': 'Daniels','modifier': '',}],'phone': [{'modifier': 'work','value': '123123123',}, {'modifier': 'work','value': '2222',}],},'type': 'person','tags': 'test'}";
try{
    URL url = new URL("https://api.nimble.com/api/v1/contact?access_token="+access_token);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type","application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    //Send Request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();
    System.out.println("Api:"+url.getHost()+url.getPath());
    System.out.println("Header:"+connection.getHeaderField("Content-Type"));
    System.out.println("content:"+connection.getContent());
    //Get Response
    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        str_response+= line + '\r';
    }
    rd.close();
}catch(Exception e){
    System.out.println("Exception:"+message);
}

I also tried change lines 13-15 with this, but the result is same:

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);

Output:

Api:api.nimble.com/api/v1/contact
Header:application/json; charset=UTF-8
Exception:Server returned HTTP response code: 409 for URL: https://api.nimble.com/api/v1/contact?access_token=38fb4aa33a101ba1c385840409a8ae7b

0条回答
登录 后发表回答