Android OKHTTP StringEntity
我正在使用OKHTTP向Microsoft文本分析API发送POST请求,但无法在OKHTTP的请求正文中找到StringEntity的对应项 我要发送的HTTP请求是:Android OKHTTP StringEntity,android,http,okhttp,microsoft-cognitive,Android,Http,Okhttp,Microsoft Cognitive,我正在使用OKHTTP向Microsoft文本分析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.c
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”:“字符串”,
“文本”:“示例字符串”
}
]?尝试以下操作:
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);