2014-04-15 55 views
0

我對這個Apache http客戶端很新。我有一個網址來對其中一個服務進行web服務調用。我成功地執行GET請求,但我試圖用POST請求執行此操作,但我沒有得到任何迴應。我無法從實體獲取內容。Apache http post example

我的網址:「https://maps.googleapis.com/maps/api/place/details/xml?reference=CoQBcQAAAEZ7yCju-0lhU7sZIBBe_On9jYImWzZ9Zt5rIg1tX6zaH02dHrQMHF1LFHY1_yUuXzsUf6m6-rrQJ8Ec_mGxBYtV85Wyb4anakaUi3QuZj7ygJXB3Fd5x69k_4UnDKMmEBNa410vbCXgQOGIkHCbNpcbC8ENxmVlUrqiifmdfuLgEhCtPATMhFRdsjuyAL_j__OEGhTnqujRRMYy_5-kxzcqCdMY4_1dbA&sensor=true&key=key1」;

這是使用GET方法執行的。下面你可以看到我的代碼。

public class HttpClientPostExample { 
public static void main(String[] args) throws ClientProtocolException, 
     IOException { 
    String url = "https://maps.googleapis.com/maps/api/place/details/xml?"; 

    HttpClient client = HttpClientBuilder.create().build(); 
    // HttpRequest httpRequest = HttpsClientImpl.createRequest("Post", url); 
    HttpPost httpPost = new HttpPost(url); 

    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); 
    nameValuePairList 
      .add(new BasicNameValuePair(
        "reference", 
        "CoQBcQAAAEZ7yCju-0lhU7sZIBBe_On9jYImWzZ9Zt5rIg1tX6zaH02dHrQMHF1LFHY1_yUuXzsUf6m6-rrQJ8Ec_mGxBYtV85Wyb4anakaUi3QuZj7ygJXB3Fd5x69k_4UnDKMmEBNa410vbCXgQOGIkHCbNpcbC8ENxmVlUrqiifmdfuLgEhCtPATMhFRdsjuyAL_j__OEGhTnqujRRMYy_5-kxzcqCdMY4_1dbA")); 
    nameValuePairList.add(new BasicNameValuePair("sensor", "true")); 
    nameValuePairList.add(new BasicNameValuePair("key", 
      "AIzaSyBA0Hu3is9qIJ5v6NEuofigk0y-aQwqiP0")); 
    httpPost.addHeader("User-Agent", "User-Agent"); 
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8")); 
    HttpResponse response = client.execute(httpPost); 
    System.out.println(response.getStatusLine().getStatusCode()); 

    Header[] headerArray = response.getAllHeaders(); 
    for (Header header : headerArray) { 
     System.out.println("Header Name: " + header.getName() 
       + " Header Value: " + header.getValue()); 
    } 
} 

任何人都可以幫助我做到這一點。這是做POST請求的正確方法...?

如何在觸發/調用執行方法之前獲取實際的URL ... ???

回答

1

嘗試從

HttpClient client = HttpClientBuilder.create().build(); 

更改client實例化技術

DefaultHttpClient client = new DefaultHttpClient(); 

,並確保你的實體已經完全消耗,撥打電話到EntityUtils.consume(entity)顯示效應初探頭前:

... 
HttpResponse response = client.execute(httpPost); 
EntityUtils.consume(response.getEntity()); 
Header[] headerArray = response.getAllHeaders(); 
for (Header header : headerArray) { 
    System.out.println("Header Name: " + header.getName() 
      + " Header Value: " + header.getValue()); 
}