如何在java中解决此HTTP GET 404错误?

时间:2012-06-09 21:08:16

标签: java apache http google-places-api

我正在使用Apache HTTPClient 4.2并尝试制作Google Places API query,但遇到问题。

以下是说明问题的基本代码:

  //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 extension中尝试了getRequestLine()网址,我会获得状态200,其数据如下所示:

    {    “html_attributions”:[],    “结果”:[],    “status”:“REQUEST_DENIED” }

  3. 但如果我使用getURI()版本,它可以正常工作。

    我不确定问题是否是附加的“HTTP / 1.1”或其他内容。 这是从Java创建Google Places API查询的正确方法吗?

1 个答案:

答案 0 :(得分: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();
        }

    }

}