简体   繁体   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";

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"我会使用这样的 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.

相关问题 如何将 IEnumurable 请求发送到 web API? - How to send IEnumurable request to a web API? 如何使用 Web Api 在 Post 请求中发送 Json - How to send Json in Post request with Web Api 如何基于Web套接字将HTTP Web请求中继到本地api - How to relay http web request to on premise api based on web sockets 如何为发送给特定用户的Web API的每个请求在服务的auto属性中保留数据? (不在会话中) - How to preserve the data in auto property in service for every request send to Web API for particular user? (not in session) Web Api中的异步HTTP请求 - Async HTTP Request in Web Api 如何将发布请求从 Android 发送到 C# Web API - How to send post request from Android to a C# web API 如何向web api 2获取请求发送整数列表? - How to send a list of integers to web api 2 get request? 如何在 C# 中使用 HTTP 请求发送 JSON GET 数据 - How to send JSON GET data with an HTTP request in C# Web API如何使用从API发送的令牌 - Web api how to use the token send from the api Web API .NET MVC - Http POST - Fiddler 请求发送字符串变量 - Web API .NET MVC - Http POST - Fiddler request send string variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM