我正在使用 Java、Spring boot 和 Apache HttpClient 嘗試發(fā)送發(fā)布請(qǐng)求。我試圖訪問(wèn)的資源的文檔可以在這里找到:https://docs.enotasgw.com.br/v2/reference#incluiralterar-empresa下面是我的代碼:CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost post = new HttpPost(incluirEmpresa);post.setHeader("Content-Type", "application/json");post.setHeader("Accept", "application/json");post.setHeader("Authorization", "Basic " + apiKey);try { StringEntity entity = new StringEntity(json); //tried to add these two lines to see if they would fix the error, but it is the same entity.setContentEncoding("application/json"); entity.setContentType("application/json"); post.setEntity(entity); System.out.println(json); System.out.println("======================"); CloseableHttpResponse response = httpClient.execute(post); System.out.println(response.getStatusLine().getReasonPhrase() + " - " + response.getStatusLine().getReasonPhrase()); idEmpresa = response.getEntity().getContent().toString();}我的回答是 400 - 錯(cuò)誤的請(qǐng)求。在上面的交互式文檔鏈接上,當(dāng)我發(fā)布我的 Json 時(shí),我收到重復(fù)條目的錯(cuò)誤,這是我所期望的,因?yàn)槲野l(fā)送的信息已經(jīng)在數(shù)據(jù)庫(kù)中。由于交互式文檔返回重復(fù)錯(cuò)誤,我知道問(wèn)題不在我的 json 格式內(nèi),而是在我的 post 請(qǐng)求中。文檔有關(guān)于 C# 的示例,但沒(méi)有關(guān)于 Java 的示例,這是我正在使用的。順便說(shuō)一句, json is variable 是一個(gè)字符串,以防萬(wàn)一。有人可以嘗試指出我的郵政編碼有什么問(wèn)題嗎?
1 回答

倚天杖
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
發(fā)現(xiàn)我錯(cuò)過(guò)了什么。在查看發(fā)送到 API 的內(nèi)容后,我注意到 json 不是預(yù)期的格式。所以我做了一些研究,發(fā)現(xiàn)至少在我的情況下,設(shè)置帶有內(nèi)容類型的標(biāo)題是不夠的,我還必須設(shè)置被設(shè)置為 HttpPost 的實(shí)體,要做到這一點(diǎn),我必須改變這個(gè)代碼行:
StringEntity entity = new StringEntity(json);
對(duì)此:
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
更改之后,請(qǐng)求開始按預(yù)期工作。
添加回答
舉報(bào)
0/150
提交
取消