簡體   English   中英

如何使用 http Web Request 向 API 發送數據?

[英]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";

我已經完成了那場比賽,但從那里我不知道該怎么做任何幫助都很棒。

這是您的案例的完整解決方案:

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 ());
}

我會使用這樣的 HttpURLConnection 來發送 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM