5

Apache HTTPClient 4.2を使用しており、 Google Places API クエリを作成しようとしていますが、問題があります。

この問題を説明するための基本的なスニペットを次に示します。

  //Web API related
  String apiKey = "API_KEY"; 
  //search params
  String location = "51.527277,-0.128625";//lat,lon
  int rad = 500;
  String types = "food";
  String name  = "pret";

  String getURL = "/maps/api/place/search/json?location="+location+"&radius="+rad+"&types="+types+"&name="+name+"&sensor=false&key="+apiKey;
  HttpHost host = new HttpHost("maps.googleapis.com",443,"https");
  HttpGet get = new HttpGet(host.toURI() + getURL);
  System.out.println("using getRequestLine(): " + get.getRequestLine());
  System.out.println("using getURI(): " + get.getURI().toString());

  DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
  try {
      HttpResponse response = httpClient.execute(get);
      System.out.println("response: " + response.getStatusLine().toString());
  } catch (Exception e) {
      System.err.println("HttpClient: An error occurred- ");
      e.printStackTrace();
  }   

私が得ているこの出力は、次のように見えます (もちろん API_KEY を除いて):

using getRequestLine(): GET https://maps.googleapis.com:443/maps/api/place/search/json?location=51.527277,-0.128625&radius=500&types=food&name=pret&sensor=false&key=API_KEY HTTP/1.1
using getURI(): https://maps.googleapis.com:443/maps/api/place/search/json?location=51.527277,-0.128625&radius=500&types=food&name=pret&sensor=false&key=API_KEY
response: HTTP/1.1 404 Not Found

次の理由から、それはすべて少し不可解です。

  1. HTTP REST 呼び出しの経験があまりない
  2. Simple REST Client Chrome 拡張機能で getRequestLine() url を試すと、次のようなデータでステータス 200 が返されます。

    { "html_attributions" : []、"results" : []、"status" : "REQUEST_DENIED" }

しかし、getURI() バージョンを使用すると、正常に動作します。

問題が追加される「HTTP/1.1」なのか、それとも何か他のものなのかはわかりません。これは Java から Google Places API クエリを作成する適切な方法ですか?

4

1 に答える 1

3

このように手動で URL を作成すると、コードが API キーを正しくエスケープしない可能性があります。また、HTTP クライアントでホストが HTTPS の場合は 433 を追加する必要もありません。動作するコードを次に示します。

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class GooglePlacesRequest {

    public static void main(String[] args) throws Exception {

        // Web API related
        String apiKey = "YOUR_API_KEY_HERE";
        // search params
        String location = "51.527277,-0.128625";// lat,lon
        String types = "food";
        String name = "pret";

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("location", location));
        parameters.add(new BasicNameValuePair("radius", "500"));
        parameters.add(new BasicNameValuePair("types", types));
        parameters.add(new BasicNameValuePair("name", name));
        parameters.add(new BasicNameValuePair("sensor", "false"));
        parameters.add(new BasicNameValuePair("key", apiKey));

        URL url = new URL(
                "https://maps.googleapis.com/maps/api/place/search/json");
        URI finalURI = URIUtils.createURI(
                url.getProtocol(), 
                url.getHost(),
                url.getPort(), 
                url.getPath(),
                URLEncodedUtils.format(parameters, "UTF-8"), 
                null);

        HttpGet get = new HttpGet(finalURI);
        System.out.println("using getRequestLine(): " + get.getRequestLine());
        System.out.println("using getURI(): " + get.getURI().toString());

        DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
        try {
            HttpResponse response = httpClient.execute(get);
            System.out.println("response: "
                    + response.getStatusLine().toString());
            System.out.println( "Response content is:" );
            System.out.println( EntityUtils.toString( response.getEntity() ) );
        } catch (Exception e) {
            System.err.println("HttpClient: An error occurred- ");
            e.printStackTrace();
        }

    }

}
于 2012-06-09T21:44:10.483 に答える