Using HttpClient and HttpPost in Android with post parameters

后端 未结 4 1714
花落未央
花落未央 2020-11-29 02:06

I\'m writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 02:21

    You can actually send it as JSON the following way:

    // Build the JSON object to pass parameters
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);
    

提交回复
热议问题