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

时间:2011-06-02 17:42:08

标签: android json post httprequest

我正试图弄清楚如何使用HTTPClient从Android发布JSON。我一直试图解决这个问题,我已经在网上找到了很多例子,但我无法让它们中的任何一个工作。我相信这是因为我缺乏一般的JSON /网络知识。我知道那里有很多例子,但有人可以指点我一个实际的教程吗?我正在寻找一步一步的过程,包括代码和解释为什么你要做每一步,或者说那个步骤做了什么。它不需要复杂,简单就足够了。

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

如果有人知道有关这方面的好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();
    }
 }

5 个答案:

答案 0 :(得分:157)

在这个答案中,我使用的是example posted by 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 Request的内容。我并不认为自己是这方面的专家,所以如果有人有更好的方式来解释某些术语,那就免费了。

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 reference。简而言之,地图类似于字典或散列。

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;
}

请随时评论关于这篇文章的任何问题,或者如果我没有做出明确的事情,或者我没有触及你仍然感到困惑的事情......等等。

(如果Justin Grammens不同意,我会退出。但如果没有,那么感谢Justin对此感到很冷静。)

更新

我刚刚发表了关于如何使用代码的评论,并意识到返回类型中存在错误。 方法签名设置为返回一个字符串,但在这种情况下它没有返回任何东西。我改变了签名 到HttpResponse并会在Getting Response Body of HttpResponse上引用您的链接 路径变量是url,我更新以修复代码中的错误。

答案 1 :(得分:41)

这是@Ttrance答案的另一种解决方案。您可以轻松地外包转换。 Gson library可以很好地将各种数据结构转换为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可以完成类似的操作。我还建议您查看Retrofit,它会为您隐藏许多样板代码。对于更有经验的开发人员,我建议您尝试RxAndroid

答案 2 :(得分:33)

我建议使用此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();
} 

答案 3 :(得分:5)

此任务的代码太多,请检查此库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();

答案 4 :(得分:3)

有几种方法可以建立HHTP连接并从RESTFULL Web服务获取数据。最近的一个是GSON。但在进入GSON之前,您必须了解创建HTTP客户端和与远程服务器进行数据通信的最传统方式。我已经提到了发送POST和amp;的两种方法。使用HTTPClient获取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;
}