How can you serialize a json object and pass it on to an api call, like the one in the example posted as an answer here Call web APIs in C# using .NET framework 3.5
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin#admin.com\",\"Password\": \"pass#123\"}")));
In Postman I would just do this
var client = new RestClient("");
var request = new RestRequest(Method.POST);
request.JsonSerializer = new RestSharpJsonNetSerializer();
request.AddJsonBody(JsonObject);
However, as Postman is not supported in .net framework 3.5, I have to use System.Net.WebClient.
You can do what you want with WebClient (and Json.NET package) like this:
var yourObject = new YourObject {
Email = "email",
Password = "password"
};
string s = client.UploadString("http://localhost:1111/Service.svc/SignIn","POST", JsonConvert.SerializeObject(yourObject));
Related
Using RestSharp 105.2.3
The API I am talking to requires use to send in a json body, but with a #c symbol as part of the field name. This is illegal in C# of course so I can't just use a dynamic object like below.
Is there a way to get the "#c" in the field name?
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
request.AddJsonBody(new
{
#c=".Something",
username="johnsmith"
});
You could just use a string like this:
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
string json = "{\"#c\":\".Something\", \"username\":\"johnsmith}";
request.AddJsonBody(json);
I Write one application to access one Webservice Restful using C#, i get the Token with success, i access other services without parameters fine, but when i need to send parameters in POST method it´s not work.
In other side, the Wesbservice dont see my post.
Can someone help-me about this ?
Here is my code.
string urlMethod = metodo;
// "/api/v1/organizacao/criar";
var accessToken = IntegraPb.GetToken();
var client = new RestClient(Sincronizador.Properties.Settings.Default.apiUrl);
var request = new RestRequest(urlMethod, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer " + accessToken);
var jsserie = new System.Web.Script.Serialization.JavaScriptSerializer();
// obj is my class to serialize
request.AddJsonBody(jsserie.Serialize(obj));
IRestResponse response = client.Execute(request);
This image is the request object
AddJsonBody receives a object, not a serialized string of your object. It does the serialization internally.
So use this instead:
request.AddJsonBody(obj);
i trying to do a simple login function.
The login will be made by an App and the information goes to a WebService (in C#).
My app is send the information to the server via HttpPost. But i can't get and return this information on the Web Service side
To make the request (android side) i was using:
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user.getText().toString()));
params.add(new BasicNameValuePair("password", pass.getText().toString()));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
On the WebService side, i was try to use the Serialize method, but it doens't work
Ps.: In order to test, i tried to run on another WebService (this one built with PHP), and works fine.
Any ideas how to make this work??
[Edit]
This is the web service side:
[HttpPost]
public string LogarAplicativo()
{
//Request.InputStream.Seek(0, SeekOrigin.Begin);
string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
dynamic data = JObject.Parse(jsonData);
//DB validation's
var json = "";
var serializer = new JavaScriptSerializer();
json = serializer.Serialize(new { success = "0", message = "Test message!" });
return json;
}
When you send information with UrlEncodedFormEntity, it will look like a the contents of an HTTP form:
param1=value1¶m2=value2
This is not JSON data, so your serialization code doesn't work because it is a completely different structure. Parsing form data requires different methods like HttpUtility.ParseQueryString.
I have developed a Web API, I can access my api by using HttpClient in .NET 4 and 4.5 but I want to access this api from an existing .NET 3.5 application. Is it possible? I have learned from internet that HttpClient is not supported in .net 3.5, so how I consume this service in .net 3.5 application?
Checkout this link for .net version 3.5:
OR TRY THIS FOR 3.5
System.Net.WebClient client = new System.Net.WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.BaseAddress = "ENDPOINT URL";
string response = client.DownloadString(string.Format("{0}?{1}", Url, parameters.UrlEncode()));
This is how I am making call in .net 4.5.
var url = "YOUR_URL";
var client = new HttpClient();
var task = client.GetAsync(url);
return task.Result.Content.ReadAsStringAsync().Result;
You could use WebRequest
// Create a request for the URL.
var request = WebRequest.Create ("http://www.contoso.com/default.html");
request.ContentType = contentType; //your contentType, Json, text,etc. -- or comment, for text
request.Method = method; //method, GET, POST, etc -- or comment for GET
using(WebResponse resp = request.GetResponse())
{
if(resp == null)
new Exception("Response is null");
return resp.GetResponseStream();//Get stream
}
i am trying to post some json to jboss services. using restSharp.. my code is as follows.
RestClient client = new RestClient(baseURL);
RestRequest authenticationrequest = new RestRequest();
authenticationrequest.RequestFormat = DataFormat.Json;
authenticationrequest.Method = Method.POST;
authenticationrequest.AddParameter("text/json", authenticationrequest.JsonSerializer.Serialize(prequestObj), ParameterType.RequestBody);
and also tried this one
RestClient client = new RestClient(baseURL);
RestRequest authenticationrequest = new RestRequest();
authenticationrequest.RequestFormat = DataFormat.Json;
authenticationrequest.Method = Method.POST; authenticationrequest.AddBody(authenticationrequest.JsonSerializer.Serialize(prequestObj));
but in both cases my server is giving me error that json is not in correct format
Try using JsonHelper to prepare your json as the following
string jsonToSend = JsonHelper.ToJson(prequestObj);
and then
authenticationrequest.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
I have found what was going wrong...
i am using RestSharp in windows metro Style, so downloaded source code and make some modifications... so that modifications in the function PutPostInternalAsync i just added this modifications
httpContent = new StringContent(Parameters[0].Value.ToString(), Encoding.UTF8, "application/json");
and it solve the problem....
Parameters[0].Value.ToString() instead of this you can write a method which can return the serialize json object. (as string).