2015-11-08 122 views
2

不確定如何將使用Java的Android查詢的POST查詢的標頭正確地放到Algolia服務器中。將JSON從HTTP Post發送到Android上的Algolia服務器

我所有關於請求頭信息從Chrome的開發者控制檯記錄網絡信息

我有查詢字符串參數:

  • X-algolia-API密鑰
  • X -algolia應用-ID
  • 的x algolia劑

和表單數據PARAMS

  • 查詢
  • hitsPerPage
  • 方面

不工作的Android代碼:

URL url = new URL(urlString); 
HttpURLConnection con = (HttpURLConnection) url.openConnection(); 

con.setRequestMethod("POST"); 
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
con.setRequestProperty("accept", "application/json"); 
con.setRequestProperty("Connection", "Keep-Alive"); 

con.setRequestProperty("query", queryString); 
con.setRequestProperty("hitsPerPage", "20"); 
con.setRequestProperty("facets", "*"); 


con.setUseCaches(false); 
con.setDoInput(true); 
con.setDoOutput(true); 

這使返回404錯誤,但很可能沒有設置正確,真正的新Android上的網絡連接,任何幫助!

+0

http錯誤404是什麼意思? – greenapps

+0

我們看不到您確實在發送json。請添加該代碼。 – greenapps

+0

'我有查詢字符串參數:'。如果你的POST沒有查詢字符串。 – greenapps

回答

3

我個人使用Algolia PHP API客戶端(位於github)以執行搜索查詢,這有助於我不必擔心REST規範。 這樣可以讓事情更容易集成到Android應用程序中,而且還集成了重試機制,可以在出現網絡問題時提高設備和API之間的連接可靠性。

相同的搜索查詢看起來像這樣:

APIClient client = new APIClient("YourApplicationID", "YourAPIKey"); 
Index index = client.initIndex("YourIndexName"); 
index.searchASync(new Query(queryString), this) 
    .setFacets("*", this) 
    .setNbHitsPerPage(20), this); 
4

你不應該做的直接請求Algolia的服務器,你會失去所有他們把發生在他們的API客戶端的logic and optimizations

使用Android API Client,做一個搜索查詢很簡單:

Index index = new APIClient("YourApplicationID", "YourAPIKey") 
     .initIndex("YourIndexName"); 
JSONObject result = index.search(new Query(queryString) 
     .setFacets("*").setHitsPerPage(20)); 

但是看看InstantSearch Android,Algolia的庫來構建搜索界面。使用它比API客戶端更容易,更快速,更安全。