What is the process of sending JSON parameters in an Android web service request?

Possible Duplicate:
How to send a JSON object over Request with Android?

Being new to Android development, I encountered an issue when trying to send requests to a web service in JSON format. After researching online, I came across this code snippet for sending requests with parameters. Below is the Java class where parameters are sent:

Main.java

RestClient client = new RestClient(LOGIN_URL);
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);

try {
  client.Execute(RequestMethod.POST);
} catch (Exception e) {
  e.printStackTrace();
}
String response = client.getResponse();

However, I am interested in sending these parameters in JSON format, like this example:

{
  "login":{
    "Email":_username,
    "Passwd":_password,
  }
}

Can anyone assist me on how to send parameters in JSON format? Any help would be greatly appreciated.

Answer №1

The code snippet provided demonstrates the utilization of Apache's HttpClient class without relying on any additional wrappers. While some may choose to use a library for convenience, in this case, using HttpClient directly is sufficient and straightforward. Below is an example of how you can make an HTTP POST request:

final String uri = "http://www.example.com";
final String body = String.format("{\"login\": {\"Email\": \"%s\", \"Passwd\": \"%s\"}", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80ede5c0e5ede1e9ecaee3efed">[email protected]</a>", "password");

final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(uri);
postMethod.setEntity(new StringEntity(body, "utf-8"));

try {
    final HttpResponse response = client.execute(postMethod);
    final String responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
    // handle exception logic here
}

It's worth noting that a JSON library would typically be used to serialize a POJO into the required JSON format for the request payload.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert JSON data into a nested unordered list

I need help converting a JSON object into an unordered list using jQuery. Here's the JSON data I have: var myJSON = "{name:\"Director\",children:[name:\"Exe Director1\",name:\"Exe Director2\",name:\"Exe Director3&bs ...

Issue in Eclipse regarding Selenium automation error

I'm encountering difficulties getting this code to function. Just a heads up, I am very new to this. package mypackage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class myclass { public static ...

What is the best method for saving this object to an SQL database?

As a newcomer to this game, I am curious to know if it's feasible to store the following object in a single column within an SQL database like postgres: { "foo1": ["bar1", "bar2"], "foo2": [" ...

Despite a valid entry from a list, the controller is receiving null values in MVC 4 with AJAX integration

I am currently developing a "create" form that includes fields for OriginAirportID and DestinationAirportID. Currently, when a user inputs a string of letters into these fields, an AJAX request is triggered to retrieve data in JSON format. This data is th ...

Exploring methods to iterate through information in a Java enumeration and display it within a VueJS component

Is it possible to display report data stored in a Java enum using Vue CLI? enumExample.java public enum DefaultFormatE { Report001 ("Report001", "HTML", "ReportName001"), Report002 ("Report002", "PDF", "ReportName002"), Report ...

What is the best way to traverse through a nested JSON file with d3.js?

Greetings. I am currently facing a challenge in navigating through a nested JSON file. Below is the JSON data that I need assistance with: {"Id":466,"Name":"korea", "Occurrences": ...

using variables as identifiers in nested JSON objects

Within my code, there is a JSON object named arrayToSubmit. Below is the provided snippet: location = "Johannesburg, South Africa"; type = "bench"; qty = 1; assetNumber = 15; arrayToSubmit = { location : { type : { 'qty' ...

Issue with List<Object> formatting in JSON is not working as expected

Currently, I am retrieving data from a ResultSet and storing it in a list: ResultSet resultSet = stmt.executeQuery(sql); List<Object> res = new ArrayList<>(); while(resultSet.next()){ res.add(resultSet.getObject(1)); } return res; ...

Encountering difficulties transmitting JSON data to the server via JavaScript

Trying to send JSON data to a server method. The method successfully works when passing a simple 'test' string, but encounters issues with the following: function SendToServer() { $.ajax({ type: "POST", url: "Default.aspx/Sa ...

Having difficulty integrating JSON data from a PHP page into jQuery

I'm having trouble parsing JSON data sent from a PHP page using jQuery. The result I'm getting is just an opening curly brace: { I'm not sure how to fix it. In my PHP code, I'm creating the JSON data like this: $load_op_cm = $DBM -> ...

GSON encountered a JsonSyntaxException, with an expectation of a name at line 7, column 4

In my project, there is a Result class that has various properties and is intended to be returned as JSON. public class Result { public String objectid; public String dtype; public String type; public String name; public String descrip ...

Adding user inputs to the tail end of API requests in Python

def i(bot,update,args): coin=args infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json() coinId = infoCall ['categories'] update.message.reply_text(coinId) An issue arises when trying to include the args specifi ...

Is there a more effective way to write and enhance the custom Json string format?

In Python 2.7, I'm constructing a json string (result of an api call) that includes a list of unanswered threads. Currently, each thread is represented as an array element, and this setup has been functioning smoothly for me. However, in my quest to e ...

Obtain the state name after selecting it from the drop-down menu and clicking the submit button (part 3)

Read more about passing city names from PHP to JS in the second part of this discussion on Stack Overflow. This is the JSON data for states ($stateJsonObject): Array ( [0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur) ...

Tips for aligning the output of a Google Translate search with the original input string

I need to translate a large number of US English strings into various other languages. I have a JSON string with the following format: "AdminLocales": { "-locale": "en_US", "global": { "search": "Search", "noOrdersFound": "No Orders Fo ...

Utilizing Date Model Binding in ASP.NET Core Framework

While working on an ASP.NET Core Web API, I encountered an issue with binding DateTime values. Specifically, I have two properties - minimumDate and maximumDate - for filtering a certain resource. These properties are part of a Filtering object that is po ...

Transforming JSON-like structure into JSON format

Recently, I came across a filtered JSON file that lost its original structure. The content of the file is presented in a way that each line looks like this: {u'spec1': {u'property1': u'12345', u'property2': ...

Getting JSON data from Redis is an essential task for any developer working

Due to using an older version of Redis that does not support the new JSON commands, I am currently resorting to using JSON.Stringify(object) and storing the data with a redis SET, resulting in a key structure like this: "{\"id\":&b ...

Is JSONP necessary for accessing the API subdomain?

Currently in the process of setting up an application with the API being hosted at http://api.project.com while the main app will reside at https://app.project.com. This app is going to be entirely based on angular.js. I'm curious if JSONP is the onl ...

Display a blank response using Dailymotion's PHP API json echo functionality

After extensively utilizing the Dailymotion json API with PHP references, I encountered an issue. When simply accessing the api url through a web browser, I could easily copy and use the "stream_h264_url" content for playback. However, when attempting to o ...