I have a library for 4.5 net fw. I need do the same but for net core.
Big beer for person which can repair this..
Code from VS with errors (screen)
MY code:
string returnData = String.Empty;
var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = method;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
string nonce = Convert.ToInt64(DateTime.Now.Ticks).ToString();
string message = nonce + url;
string signature = HashEncode(HashHMAC(StringEncode(API_SECRET), StringEncode(message)));
var whc = new WebHeaderCollection();
whc.Add("ACCESS_KEY: " + API_KEY);
whc.Add("ACCESS_SIGNATURE: " + signature);
whc.Add("ACCESS_NONCE: " + nonce);
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
You can use my code as below. Hope to help, my friend:
var webRequest = WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Accept = "*/*";
webRequest.UserAgent = ".NET";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/json";
webRequest.Host = "coinbase.com";
var whc = new WebHeaderCollection
{
"ACCESS_KEY: " + API_KEY,
"ACCESS_SIGNATURE: " + signature,
"ACCESS_NONCE: " + nonce
};
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
Related
i try to make an HTTP POST to an Swagger UI api and wrote this rudimentary Code:
string baseip = "192.168.0.1";
string auth = "authcodre";
string name = "TestMan";
string ip = "1.1.1.1";
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string URL = "https://" + baseip + ":4444/api/objects/network/host/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.ContentType = "application/json";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("token:" + auth));
request.PreAuthenticate = true;
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string patchtxt = "{ \"name\": \"" + name + "\", \"_type\": \"network/host\", \"address\": \"" + ip + "\"}";
streamWriter.Write(patchtxt);
streamWriter.Flush();
streamWriter.Close();
Console.WriteLine("Patches");
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); //Einlesen der HTTP-Antwort
string resppatch = reader.ReadToEnd();
Console.WriteLine(resppatch);
Console.ReadLine();
}
It throws me an System.IO.IOException" in mscorlib.dll at this line:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
Can anyone explain why this happens and how to fix it?
Thank you :)
I have a function to call my Web API. It works well if TestCallingRemotely is set to [AllowAnonymous].
var httpWebRequest = (HttpWebRequest)WebRequest.Create(
"http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
string input = "{}";
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
How do I pass the username and password to the HttpWebRequest for authorization?
I need to call my Web API from CLR integration, which only supports System.Net.
ABP's startup template uses bearer token authentication infrastructure.
var token = GetToken(username, password);
// var httpWebRequest = (HttpWebRequest)WebRequest.Create(
// "http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
// httpWebRequest.ContentType = "application/json";
// httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
// ...
Get token
This uses a crude way to extract the token, inspired by an MSDN article.
private string GetToken(string username, string password, string tenancyName = null)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(
"http://localhost:6334/api/Account/Authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var input = "{\"usernameOrEmailAddress\":\"" + username + "\"," +
"\"password\":\"" + password + "\"}";
if (tenancyName != null)
{
input = input.TrimEnd('}') + "," +
"\"tenancyName\":\"" + tenancyName + "\"}";
}
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string response;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
// Crude way
var entries = response.TrimStart('{').TrimEnd('}').Replace("\"", String.Empty).Split(',');
foreach (var entry in entries)
{
if (entry.Split(':')[0] == "result")
{
return entry.Split(':')[1];
}
}
return null;
}
If the server uses basic authentication you can add the header like this:
var httpWebRequest = (HttpWebRequest) WebRequest.Create(
"http://localhost/api/services/myApp/commonLookup/TestCallingRemotely");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var username = "Aladdin";
var password = "opensesame";
var bytes = Encoding.UTF8.GetBytes($"{username}:{password}");
httpWebRequest.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(bytes)}");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string input = "{}";
streamWriter.Write(input);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
public void processVoucher()
{
try
{
string url = "http://192.168.xxx.xx:xxxx/context-root-xxxxxxxx/AccountsPayableManagerPort?WSDL/processVoucher";
StreamReader str = new StreamReader(#"F:\IntelliChief integration to JD Edwards for AP Invoice entry\processVoucher_input_payload.xml");
string ipParameter = str.ReadToEnd();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/xml";
req.KeepAlive = true;
req.Timeout = 30000;
req.Accept = "application/xml";//"text/xml";
req.Headers.Clear();
req.Method = "POST";
Encoding encode = Encoding.GetEncoding("utf-8");
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(ipParameter);
}
}
var response = req.GetResponse(); // here i am getting Unsupported Media Type issue
Stream responseStream = response.GetResponseStream();
StreamReader strReader = new StreamReader(responseStream, encode, true);
string result = strReader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show("Error Message:" + ex.Message);
throw;
}
}
I got requirement of consuming web service, display the result, i am trying to consume web service by using HttpWebRequest class. I running exception in req.GetResponse() any help is appreciated.
public void processVoucher()
{
string soap = null;
try
{
StreamReader str = new StreamReader(#"F:\xxx\some.xml");
soap = str.ReadToEnd();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://192.168.xxx.xx:xxxx/bla-bla-bla/AccountsPayableManagerPort?WSDL");
req.ContentType = "text/xml;charset=\"UTF-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soap);
}
}
using (WebResponse response = req.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
}
}
}
catch (Exception)
{
throw;
}
}
Finally i found solution to the issue, above is the working code. After i changed req.ContentType = "application/xml"; to req.ContentType = "text/xml;charset=\"UTF-8\""; , req.Accept = "application/xml"; to req.Accept = "text/xml"; and i removed req.Headers.Clear(); my code started working thanks all for your support...
I am trying to Shim the following code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + authToken.token.access_token);
request.Accept = "application/json";
But running the Unit Test throws an exception in this part: request.Headers.Add() because request.Headers is null. This, in spite of initializing Headers in my test:
ShimHttpWebRequest request = new ShimHttpWebRequest();
ShimWebRequest.CreateString = (urio) => {
request.Instance.Headers = new WebHeaderCollection {
{"Authorization", "Bearer abcd1234"}
};
//also tried initilizing it like this:
//WebHeaderCollection headers = new WebHeaderCollection();
//headers[HttpRequestHeader.Authorization] = "Bearer abcd1234";
//request.Instance.Headers = headers;
return request.Instance;
};
But request.Instance.Headers is still null.
What am I missing?
I solved this by creating a getter for Headers so that it would return a WebHeaderCollection instead of null.
ShimHttpWebRequest request = new ShimHttpWebRequest();
ShimWebRequest.CreateString = (urio) => request.Instance;
request.HeadersGet = () => {
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization", "Bearer abcd1234");
return headers;
};
I solved this by instantiating Header property of ShimHttpWebRequest as follows,
var httpWebRequest = new ShimHttpWebRequest() { HeadersGet = () => new WebHeaderCollection() };
ShimWebRequest.CreateString = (arg1) => httpWebRequest.Instance;
This is my code, you can try it:
public static string HttpPostWebRequest(string requestUrl, int timeout, string requestXML, bool isPost, string encoding, out string msg)
{
msg = string.Empty;
string result = string.Empty;
try
{
byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = requestUrl;
request.Method = isPost ? "POST" : "GET";
request.ContentLength = bytes.Length;
request.Timeout = timeout * 1000;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding));
result = reader.ReadToEnd();
reader.Close();
responseStream.Close();
request.Abort();
response.Close();
return result.Trim();
}
}
catch (Exception ex)
{
msg = ex.Message + ex.StackTrace;
}
return result;
}
I need to call a method from a webservice, so I've written this code:
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.
webRequest.ContentLength = 0;
WebResponse webResponse = webRequest.GetResponse();
But this method requires some parameters, as following:
Post data:
_username:'API USER', // api authentication username
_password:'API PASSWORD', // api authentication password
How can I add these parameters into this Webrequest?
Use stream to write content to webrequest
string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();
If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.
If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:
private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri)
{
var result = "";
if (!string.IsNullOrEmpty(requestUri))
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
if (request != null)
{
request.KeepAlive = true;
var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.CachePolicy = cachePolicy;
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
request.Timeout = Constants.RequestTimeOut;
if (request.Method == "POST")
{
if (postData != null)
{
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}
}
}
using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (httpWebResponse != null)
{
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
}
}
responseUri = null;
return null;
}
For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.
Hope this works
webRequest.Credentials= new NetworkCredential("API_User","API_Password");
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()