Search Documents (Azure Cognitive Search REST API) https://docs.microsoft.com/en-us/rest/api/searchservice/Search-Documents
I was a little addicted to the fact that the URL was different when making a POST request.
package hello;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.gson.JsonObject;
public class HelloAzurePostSearch {
public static void main(String[] args) throws Exception {
//Official documentation
// https://docs.microsoft.com/en-us/rest/api/searchservice/Search-Documents
// POST https://[service name].search.windows.net/indexes/[index name]/docs/search
// ?api-version=[api-version]
// Content-Type: application/json
// api-key: [admin or query key]
String serviceName = "{your service name}";
String indexName = "{your index name}";
String apiVersion = "2019-05-06";
String adminKey = "{your admin key}";
URIBuilder builder = new URIBuilder("https://" + serviceName + ".search.windows.net" //
+ "/indexes/" + indexName + "/docs" //
+ "/search" //← Note that the URL is different between GET and POST!
) //
.addParameter("api-version", apiVersion);
JsonObject requestBody = new JsonObject();
{
requestBody.addProperty("search", "*");
requestBody.addProperty("count", true);
}
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(builder.build());
httpPost.addHeader("api-key", adminKey);
StringEntity requestEntity //
= new StringEntity(requestBody.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
CloseableHttpResponse response = client.execute(httpPost);
System.err.println(response.getStatusLine().getStatusCode());
// response body
System.err.println(EntityUtils.toString(response.getEntity()));
client.close();
}
}
Recommended Posts