How to send a name value pair Object or content values object using post in android api 23 using HttpUrl connection?

前端 未结 1 1585
栀梦
栀梦 2021-01-29 06:35

//Here is what i have tried. // I don\'t know how to append inputurl and Content values and send this to server using HttpURLConnection.

public JSONObject getJsonFromUr

相关标签:
1条回答
  • 2021-01-29 07:05

    if you want to post a JSON object to an url though HttpUrlConnection instance you can write is like this.

        DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
        wr.writeBytes(jsonObject.toString());
        wr.flush();
        wr.close();
    Where,
    
    jsonObject is the json object which you would be posting to the URL 
    

    the entire code may look like this

    URL url = new URL("this would be your url where you want to POST");
    
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    // when you are posting do make sure you assign appropriate header
    // In this case POST.
    
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.connect();
    
    // like this you can create your JOSN object which you want to send
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("email", "ffffdd@gmail.com");
    jsonObject.addProperty("password", "password");
    
    // And this is how you will write to the URL
    DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
    wr.writeBytes(jsonObject.toString());
    wr.flush();
    wr.close();
    
    Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));
    
    0 讨论(0)
提交回复
热议问题