将JSON从HTTP Post发送到Android上的Algolia服务器

问题描述:

不确定如何将使用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

我个人使用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); 

你不应该做的直接请求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客户端更容易,更快速,更安全。