How to send a JSON object over HttpClient Request with Android?

后端 未结 3 997
無奈伤痛
無奈伤痛 2020-12-16 14:39

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content h

相关标签:
3条回答
  • 2020-12-16 15:12

    If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++

    If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library. However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/

    If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?

    If its a REST-API Call like POST or GET to be more specific then its is very simple Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.

    Hope this helps.

    0 讨论(0)
  • 2020-12-16 15:24

    In the try catch loop, I did this:

             HttpPost post = new HttpPost(
             "https://www.placeyoururlhere.com");
             post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
             List<NameValuePair> nameValuePairs = new
             ArrayList<NameValuePair>(1);
             nameValuePairs.add(new BasicNameValuePair("json", json));
             post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
             HttpClient client = new DefaultHttpClient();
             HttpResponse resp = client.execute(post);
             HttpEntity entity = resp.getEntity();
    
             response = EntityUtils.toString(entity);
    

    You can add your nameValurPairs according to how many fields you have. Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.

    0 讨论(0)
  • 2020-12-16 15:25

    I do this with

    httppost.setHeader("Content-type", "application/json");
    

    Also, the new HttpPost() takes the web service URL as argument.

    0 讨论(0)
提交回复
热议问题