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”:[],“结果”:[],“状态”:“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 回答