如何在Android中使用HTTPClient在JSON中发送POST请求?

我想弄清楚如何使用HTTPClient从Android POST JSON。 我一直在试图弄清楚这一点,我已经在网上find了很多例子,但是我不能让它们中的任何一个工作。 我相信这是因为我缺乏一般的JSON /networking知识。 我知道有很多例子,但有人可以指点我一个实际的教程? 我正在寻找一个循序渐进的过程,使用代码和解释为什么你要做每一步,或者该步骤做什么。 它不需要是一个复杂的,简单的就够了。

再次,我知道这里有很多例子,我只是在寻找一个例子来解释究竟发生了什么以及为什么这样做。

如果有人知道关于此的一本好Android书,请让我知道。

再次感谢@terrance的帮助,这里是我在下面描述的代码

public void shNameVerParams() throws Exception{ String path = //removed HashMap params = new HashMap(); params.put(new String("Name"), "Value"); params.put(new String("Name"), "Value"); try { HttpClient.SendHttpPost(path, params); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

在这个答案中,我正在使用Justin Grammens发布的一个例子 。

关于JSON

JSON代表JavaScript Object Notation。 在JavaScript属性中可以像这个object1.name一样被引用,就像这个object['name']; 。 本文中的示例使用了这一点的JSON。

零件
电子邮件作为密钥,foo@bar.com作为值的粉丝对象

 { fan: { email : 'foo@bar.com' } } 

所以这个对象相当于fan.email;fan['email']; 。 两者都有相同的价值'foo@bar.com'

关于HttpClient请求

以下是我们作者用来制作HttpClient请求的内容 。 我不认为自己是一个专家,所以如果任何人有更好的方式来免费的话来说一些术语。

 public static HttpResponse makeRequest(String path, Map params) throws Exception { //instantiates httpclient to make request DefaultHttpClient httpclient = new DefaultHttpClient(); //url with the post data HttpPost httpost = new HttpPost(path); //convert parameters into JSON object JSONObject holder = getJsonObjectFromMap(params); //passes the results to a string builder/entity StringEntity se = new StringEntity(holder.toString()); //sets the post request as the resulting string httpost.setEntity(se); //sets a request header so the page receving the request //will know what to do with it httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/json"); //Handles what is returned from the page ResponseHandler responseHandler = new BasicResponseHandler(); return httpclient.execute(httpost, responseHandler); } 

地图

如果您对Map数据结构不熟悉,请查看Java Map参考 。 简而言之,地图类似于字典或散列。

 private static JSONObject getJsonObjectFromMap(Map params) throws JSONException { //all the passed parameters from the post request //iterator used to loop through all the parameters //passed in the post request Iterator iter = params.entrySet().iterator(); //Stores JSON JSONObject holder = new JSONObject(); //using the earlier example your first entry would get email //and the inner while would get the value which would be 'foo@bar.com' //{ fan: { email : 'foo@bar.com' } } //While there is another entry while (iter.hasNext()) { //gets an entry in the params Map.Entry pairs = (Map.Entry)iter.next(); //creates a key for Map String key = (String)pairs.getKey(); //Create a new map Map m = (Map)pairs.getValue(); //object for storing Json JSONObject data = new JSONObject(); //gets the value Iterator iter2 = m.entrySet().iterator(); while (iter2.hasNext()) { Map.Entry pairs2 = (Map.Entry)iter2.next(); data.put((String)pairs2.getKey(), (String)pairs2.getValue()); } //puts email and 'foo@bar.com' together in map holder.put(key, data); } return holder; } 

请随时评论有关这篇文章的任何问题,或者如果我没有说清楚什么,或者如果我没有触及你仍然困惑的事情,等等。

(如果贾斯汀·格拉门斯不赞成的话,我会下台,但是如果没有,那么感谢贾斯汀对此很冷静。)

更新

我只是想知道如何使用代码,并意识到返回types有错误。 方法签名被设置为返回一个string,但在这种情况下,它没有返回任何东西。 我将签名更改为HttpResponse,并将引用您对此链接获取HttpResponse的响应正文pathvariables是URL,我更新以修复代码中的错误。

这是@ Terrance的答案的另一种解决scheme。 您可以轻松地将转换外包。 Gson库做了很好的工作,将各种数据结构转换成JSON, 反之亦然 。

 public static void execute() { Map<String, String> comment = new HashMap<String, String>(); comment.put("subject", "Using the GSON library"); comment.put("message", "Using libraries is convenient."); String json = new GsonBuilder().create().toJson(comment, Map.class); makeRequest("http://192.168.0.1:3000/post/77/comments", json); } public static HttpResponse makeRequest(String uri, String json) { try { HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(new StringEntity(json)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); return new DefaultHttpClient().execute(httpPost); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } 

类似的可以通过使用jackson而不是Gson来完成。 我也build议看看Retrofit ,它隐藏了很多这样的样板代码给你。 对于更有经验的开发人员,我build议尝试使用RxAndroid 。

我build议使用这个HttpURLConnection而不是HttpGet 。 由于HttpGet已经在Android API级别22中被弃用了。

 HttpURLConnection httpcon; String url = null; String data = null; String result = null; try { //Connect httpcon = (HttpURLConnection) ((new URL (url).openConnection())); httpcon.setDoOutput(true); httpcon.setRequestProperty("Content-Type", "application/json"); httpcon.setRequestProperty("Accept", "application/json"); httpcon.setRequestMethod("POST"); httpcon.connect(); //Write OutputStream os = httpcon.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(data); writer.close(); os.close(); //Read BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8")); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); result = sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

这个任务的代码太多,检出这个库https://github.com/kodart/Httpzoid在内部使用GSON,并提供与对象一起工作的API。; 所有的JSON细节都是隐藏的。

 Http http = HttpFactory.create(context); http.get("http://example.com/users") .handler(new ResponseHandler<User[]>() { @Override public void success(User[] users, HttpResponse response) { } }).execute(); 

有几种方法可以build立HHTP连接并从RESTFULL Web服务获取数据。 最近的是GSON。 但在进行GSON之前,您必须了解创buildHTTP客户端并与远程服务器进行数据通信的最传统方法。 我已经提到了使用HTTPClient发送POST和GET请求的方法。

 /** * This method is used to process GET requests to the server. * * @param url * @return String * @throws IOException */ public static String connect(String url) throws IOException { HttpGet httpget = new HttpGet(url); HttpResponse response; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 60*1000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 60*1000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); result = convertStreamToString(instream); //instream.close(); } } catch (ClientProtocolException e) { Utilities.showDLog("connect","ClientProtocolException:-"+e); } catch (IOException e) { Utilities.showDLog("connect","IOException:-"+e); } return result; } /** * This method is used to send POST requests to the server. * * @param URL * @param paramenter * @return result of server response */ static public String postHTPPRequest(String URL, String paramenter) { HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 60*1000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 60*1000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(URL); httppost.setHeader("Content-Type", "application/json"); try { if (paramenter != null) { StringEntity tmp = null; tmp = new StringEntity(paramenter, "UTF-8"); httppost.setEntity(tmp); } HttpResponse httpResponse = null; httpResponse = httpclient.execute(httppost); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream input = null; input = entity.getContent(); String res = convertStreamToString(input); return res; } } catch (Exception e) { System.out.print(e.toString()); } return null; }