Ich bin Anfänger und erstelle Winform-Anwendung. In dem ich API für Simple CRUD verwenden muss. Mein Client hatte die API mit mir geteilt und bat, Daten in Form von JSON zu senden.
API: http://blabla.com/blabla/api/login-valida
SCHLÜSSEL: "HelloWorld"
Wert: {"email": "[email protected]", "password": "123456", "time": "2015-09-22 10:15:20"}
Antwort: Login_id
Wie kann ich Daten in JSON konvertieren, die API mit der Methode POST aufrufen und eine Antwort erhalten?
EDIT Irgendwo im stackoverflow habe ich diese Lösung gefunden
public static void POST(string url, string jsonContent)
{
url="blabla.com/api/blala" + url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = @"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch
{
throw;
}
}
//on my login button click
private void btnLogin_Click(object sender, EventArgs e)
{
CallAPI.POST("login-validate", "{ \"email\":" + txtUserName.Text + " ,\"password\":" + txtPassword.Text + ",\"time\": " + DateTime.Now.ToString("yyyy-MM-dd h:mm tt") + "}");
}
Ich habe eine Ausnahme erhalten, die besagt "Der Remote-Server hat einen Fehler zurückgegeben: (404) Not Found".
Sie können einen Blick darauf werfen
Als Erstes müssen Sie die Web API-Clientbibliotheken installieren:
Wählen Sie im Menü Extras den Befehl Library Package Manager und dann Package Manager Console. Geben Sie im Fenster der Package Manager Console den folgenden Befehl ein:
Install-Package Microsoft.AspNet.WebApi.Client
Dann sende eine Post-Anfrage wie diese
// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri gizmoUrl = response.Headers.Location;
}
Verwenden Sie einfach die folgende Bibliothek.
https://www.nuget.org/packages/RestSharp
GitHub-Projekt: https://github.com/restsharp/RestSharp
Beispielcode::
public Customer GetCustomerDetailsByCustomerId(int id)
{
var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
var request = new RestRequest(Method.GET);
request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
dynamic json = JsonConvert.DeserializeObject(content);
JObject customerObjJson = jsonData.CustomerObj;
var customerObj = customerObjJson.ToObject<Customer>();
return customerObj;
}