我正在使用OKHTTP向Microsoft Text Analytics API发送POST请求,但无法找出OKHTTP请求正文中StringEntity的对应项。
我想发送的HTTP请求是:
POST https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages?numberOfLanguagesToDetect=1 HTTP/1.1
Content-Type: application/json
Host: westus.api.cognitive.microsoft.com
Ocp-Apim-Subscription-Key: ••••••••••••••••••••••••••••••••
{
"documents": [
{
"id": "string",
"text": "example string"
}
]
}
我现在写的方式是:
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages").newBuilder();
urlBuilder.addQueryParameter("numberOfLanguagesToDetect", "1");
String url = urlBuilder.build().toString();
JSONObject text = new JSONObject();
text.put("id", "string");
text.put("text", "example string");
MediaType jsonMT = MediaType.parse("application/json; charset=utf-8");
RequestBody rBody = RequestBody.create(jsonMT, text.toString());
Request request = new Request.Builder()
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", sub-key)
.url(url)
.post(rBody)
.build();
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
然而,这是不正确的。如何格式化我的请求正文以使其成为“文档”:[ { “id”:“string”, “text”:“示例字符串” } ]
答案 0 :(得分:0)
尝试以下方法:
JSONObject document = new JSONObject();
document.put("id", "string");
document.put("text", "example string");
JSONArray documents = new JSONArray();
documents.put(document);
JSONObject root = new JSONObject();
root.put("documents", documents);