How to post json object to servlet?

TingZengTingZeng USMember ✭✭

My Xamarin side of code :

public class SendData{

public int TransactionId { set; get; }
public float DollarAmount { set; get; }

}

public async Task SendAjax(){

    HttpClient oHttpClient = new HttpClient();

    SendData data = new SendData();
    data.TransactionId = 4;
    data.DollarAmount = (float) 1111.11;

    var temp = "{\"TransactionId\", 4}";
    var sData = JsonConvert.SerializeObject(data);

    oJsonObject.Add("jsondata",sData);
    var oTaskPostAsync = oHttpClient.PostAsync(serverURL, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType))

Servlet side:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Object myObj = request.getParameter("jsondata");

}

I got null for myObj. I tried directly add TransactionId to the oJsonObject, and read TransactionId on servlet, still null data.

Any idea ? It is driving me nuts. Thx.

Posts

  • XavierPerseguersXavierPerseguers CHMember ✭✭✭

    I'm doing it like that and it works in my app:

    var payload = JsonConvert.SerializeObject(data);
    
    StringContent contents = new StringContent(payload, System.Text.Encoding.UTF8);
    contents.Headers.ContentType = "application/json";
    
    string responseBody = null;
    HttpResponseMessage response = null;
    
    try {
        response = await Client.PostAsync(requestUri, contents);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        response.EnsureSuccessStatusCode();
        responseBody = await response.Content.ReadAsStringAsync();
        response.Dispose();
    } catch (HttpRequestException hre) {
    }
    
  • TingZengTingZeng USMember ✭✭

    Thanks for replying. I found a solution myself. I have not tried yours, I will give it a shot later.

    public async Task SendAjax(IEnumerable<KeyValuePair<string, string>> dataPairs){

       HttpClient oHttpClient = new HttpClient();
        var content = new FormUrlEncodedContent(dataPairs);
            var oTaskPostAsync = oHttpClient.PostAsync(serverURL, content);
    
            var response = await oTaskPostAsync;
    
            var result = await response.Content.ReadAsStringAsync();
    
            return result;
    

    }

    The key is to embed the data in a form format and send. This is because the receiver end is a servlet doPost(HttpServletRequest request, HttpServletResponse response).

    So far, I found the servlet only works well with either query data (embedded in query or form data). If Json data, I can only get it to work with Json sent by Javascript.

  • TingZengTingZeng USMember ✭✭

    Just tried your solution, it is the same error I got before. The Json data would not be interpreted correctly. All are null values on Servlet side. Form data works. Hope this would help someone who has the same issue.

Sign In or Register to comment.