简体   繁体   中英

How to use http Web Request to Send data to API?

var update = new update();
update.name = "Test Name";

//Serialize
string json = JsonConvert.SerializeObject(update);


WebRequest request = WebRequest.Create("api.example.com/profiles/1");
request.ContentType = "text/json";
request.Method = "PATCH";

I have got that match going but from there i am not sure what to do any help is great.

This is the whole solution for your case:

var update = new update();
update.name = "Test Name";
    
var httpWebRequest = HttpWebRequest.Create ("api.example.com/profiles/1") as HttpWebRequest;


httpWebRequest.Method = "PATCH";
httpWebRequest.ContentType = "text/json";
httpWebRequest.Timeout = 5000;

using (var streamWriter = new StreamWriter (httpWebRequest.GetRequestStream ())) {
    streamWriter.Write (JsonConvert.SerializeObject(update));
}

using (WebResponse response = httpWebRequest.GetResponse ()) {
    streamReader = new StreamReader (response.GetResponseStream ());
    var objectResponse = JsonConvert.DeserializeObject<your_object> (streamReader.ReadToEnd ());
}

I would use a HttpURLConnection like this to send name="test name"

    String urlParameters = "name="+URLEncoder.encode("test name", "UTF-8");
    URL obj = new URL("api.example.com/profiles/1");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM