I'm trying to make POST to an external webapi sending "raw" data. I could successfully do it using for example Postman, but when I tried to do it in my MVC App, I get the following error: Specified value does not have a ':' separator. Parameter name: header.
This is my code for calling the webapi:
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
string postData = pToken;
//I THINK THE ERROR IS IN THE NEXT LINE:
request.Headers.Add(postData);
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
Write the pToken variable to request stream
PSUEDO CODE
public UserCustom GetUserByToken(string pToken)
{
ResponseLogin vRespuesta = new ResponseLogin();
UserCarmocal vUsuarioFinal = null;
string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
WebRequest request = WebRequest.Create(vDirUser);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("ApiKey", vApiKey);
var bytes = System.Text.Encoding.UTF8.GetBytes(pToken);
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
using (Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
if (vRespuesta.status == "success")
{ vUsuarioFinal.FirstName = "Test"; }
}
}
return vUsuarioFinal;
}
Related
I'm trying to get the response from an http api rest link, but i don't know why, the response is empty, even testing the endpoint on postman and in my browser, that returns the correct. The code i'm using for getting the response is:
private static string connect(string url, string method, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json";
request.Accept = "application/json";
if (data.Length > 0)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
}
using (WebResponse response = request.GetResponse())
{
using (Stream strReader = response.GetResponseStream())
{
if (strReader == null) return "";
using (StreamReader objReader = new StreamReader(strReader))
{
return JsonConvert.DeserializeObject<Response>(objReader.ReadToEnd()).data; //objReader.ReadToEnd();
}
}
}
}
And calling it like this:
String response = connect("http://31.214.245.211:8080/ProjectM-WS/webservice/rest/ping", "GET", "");
Any idea of where I can be wrong?
Thank you for the help!
Thought that didn't work, that's becouse i commented it, but now it does.
private static string connect(string url, string method, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json";
request.Accept = "application/json";
if (data.Length > 0)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
}
using (WebResponse response = request.GetResponse())
{
using (Stream strReader = response.GetResponseStream())
{
if (strReader == null) return "";
using (StreamReader objReader = new StreamReader(strReader))
{
return objReader.ReadToEnd();
}
}
}
}
I need to make an rpc to a thirh party API and send the following JSON
{
"jsonrpc":"2.0",
"id":"number",
"method":"login.user",
"params":{
"login":"string",
"password":"string"
}
}
I have created a method to make the rcp but i cannot get the correct JSON to be send
public JObject Post()
{
object[] a_params = new object[] { "\"login\" : \"test#test.ru\"", "\"password\": \"Password\""};
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0");
webRequest.ContentType = "application/json; charset=UTF-8";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = 1;
joe["method"] = "login.user";
if (a_params != null)
{
if (a_params.Length > 0)
{
JArray props = new JArray();
foreach (var p in a_params)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
string s = JsonConvert.SerializeObject(joe);
// serialize json for the request
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
WebResponse webResponse = null;
try
{
using (webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
}
catch (WebException webex)
{
using (Stream str = webex.Response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
var tempRet = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
return tempRet;
}
}
}
catch (Exception)
{
throw;
}
}
With my code i'm getting the following JSON
{"jsonrpc":"2.0","id":1,"method":"login.user","params":["\"login\" : \"v.ermachenkov#mangazeya.ru\"","\"password\": \"AmaYABzP2\""]}
As i understand my error is that params is an array([]) instead of an object({}). Based on my method how can get the correct json?
I correct my mistake. The code shoukd be
JObject a_params = new JObject { new JProperty("login", "login"), new JProperty("password", "Password") };
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0");
webRequest.ContentType = "application/json; charset=UTF-8";
webRequest.Method = "POST";
JObject joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = "1";
joe["method"] = "login.user";
joe.Add(new JProperty("params", a_params));
I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);
I want to send message on facebook. This is my method to make a post request:
public static string http_post(string url, string data)
{
var cookiespost = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookiespost;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write(data);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
cookies = cookiespost;
return result;
}
}
data:
"fb_dtsg=AQHcmRlBsZsj&charset_test=%E2%82%AC%2C%C2%B4%2
C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84&ids%
5B100002079663653%5D=100002079663653&text_ids%
5B100002079663653%5D=%D0%9D%D0%B8%D0%BA%D0%B8%D1%
82%D0%B0+%D0%A5%D0%B8%D0%B6%D0%BD%D1%8F%D0%BA&body="
+ textofmessage + "&Send=%D0%9D%D0%B0%D0%B4%
D1%96%D1%81%D0%BB%D0%B0%D1%82%D0%B8";
url:
https://m.facebook.com/messages/send/?icm=1
But the message is not sent in the text of the response I get login page.
How is it possible to perform sending a message ?
Thanks!
I want to post a request on server using POST and webrequest?
I need to pass parameters as well while posting?
how can i pass the parameters while posting?
How can i do that???
Sample code...
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
you can try with this code
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();