2017-04-30 4 views
0

Ich verwende OKHTTP, um POST-Anfragen an Microsoft Text Analytics API zu senden, kann aber das Gegenstück von StringEntity im OKHTTP-Anfragetext nicht ermitteln.Android OKHTTP StringEntity

Die HTTP-Request ich senden möchte, ist:

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" 
     } 
     ] 
    } 

So wie ich jetzt geschrieben ist:

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(); 

Dies ist jedoch falsch. Wie kann ich meinen Anfragetext so formatieren, dass er "Dokumente" ist: [ { "id": "string", "text": "beispiel string" } ]?

Antwort

0

Versuchen Sie Folgendes:

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); 
+0

Dank! Es funktioniert jetzt! –

Verwandte Themen