0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Azure Search + Java Apache HttpClient で POSTリクエストによる検索

Posted at

#公式ドキュメント

Search Documents (Azure Cognitive Search REST API)
https://docs.microsoft.com/en-us/rest/api/searchservice/Search-Documents

#結論

POSTリクエストのときはURLが違うというところに少しハマりました。

#コード


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 {

// 公式ドキュメント
// 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" // ←GETとPOSTでURLが異なる点に注意!
		) //
				.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();

	}

}


##以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?