可能な限り簡単な方法で、ボディ リクエストで JSON 文字列を送信する HTTP POST を作成する必要があります。API は次のとおりです: 'api.nimble.com/api/v1/contact' ( https://nimble.readthedocs.org/en/latest/contacts/basic/create/ )。
JSON は文字列変数 (追加のライブラリを使用する必要はありません) であり、リクエストの本文で送信する必要があります。
次の Java コードがありますが、常に 409 HTTP ERROR を返します。
正しく動作するためにコードを変更/追加する必要があることを誰かが教えてくれますか? どうもありがとう!
更新: ソリューションはhttp://jsonlint.com/で検証されます。正しい JSON 文字列は次のとおりです (二重引用符をエスケープし、フィールドの末尾にあるコンマを削除します)。
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\"}";
コード:
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);
}
これで13〜15行目を変更しようとしましたが、結果は同じです:
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
出力:
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