Turning HttpWebResponse into an HttpResponseMessage - c#

I have the following action in an asp.net WebAPI controller:
public HttpResponseMessage GetCBERSS(string Site, string File, string User, string Password)
{
string URLString = string.Format("https://{0}.rss.mycompany.com/{1}", Site, File);
Uri uri = new Uri(URLString);
CredentialCache cache = new CredentialCache();
cache.Add(uri, "Basic", new NetworkCredential(User, Password));
WebRequest r = WebRequest.Create(uri);
r.Credentials = cache;
r.ContentType = "application/rss+xml";
IgnoreBadCertificates();
HttpWebResponse result = (HttpWebResponse)r.GetResponse();
return ???;
}
How can I convert the HttpWebResponse into an HttpResponseMessage?

The best way to transform HttpWebResponse in HttpResponseMessage is create a new HttpResponseMessage :
using (var responseApi = (HttpWebResponse)request.GetResponse())
{
var response = new HttpResponseMessage(responseApi.StatusCode);
using (var reader = new StreamReader(responseApi.GetResponseStream()))
{
var objText = reader.ReadToEnd();
response.Content = new StringContent(objText, Encoding.UTF8, "application/json");
}
return response;
}

Related

Bitstamp API POST request with parameters

please, help me with POST api request in C#.I dont know how to correctly send parameters „key“, „signature“ and „nonce“ in POST request. It constantly tells me "Missing key, signature and nonce parameters“.
HttpWebRequest webRequest =(HttpWebRequest)System.Net.WebRequest.Create("https://www.bitstamp.net/api/balance/");
if (webRequest != null)
{
webRequest.Method = HttpMethod.Post;
webRequest.ContentType = "application/json";
webRequest.UserAgent = "BitstampBot";
byte[] data = Convert.FromBase64String(apisecret);
string nonce = GetNonce().ToString();
var prehash = nonce + custID + apikey;
string signature = HashString(prehash, data);
body = Serialize(new
{
key=apikey,
signature=signature,
nonce=nonce
});
if (!string.IsNullOrEmpty(body))
{
var data1 = Encoding.UTF8.GetBytes(body);
webRequest.ContentLength = data1.Length;
using (var stream = webRequest.GetRequestStream()) stream.Write(data1, 0, data1.Length);
}
using (Stream s = webRequest.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
contentBody = await sr.ReadToEndAsync();
return contentBody;
}
}
}
The "Request parameters" as Bitstamp specifies in the docs is actually supposed to be sent with content type "application/x-www-form-urlencoded" instead of "application/json".
I would also use HttpClient to perform the post as that has a much more simple setup to perform Http requests
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key", apikey),
new KeyValuePair<string, string>("signature", signature),
new KeyValuePair<string, string>("nonce", nonce)
});
var result = await client.PostAsync("https://www.bitstamp.net/api/balance/", content);
string resultContent = await result.Content.ReadAsStringAsync();
}

How to consume rest api in C#

I want to consume rest api having post method in my project (web)/Windows service(C#).
Url : https://sampleurl.com/api1/token
I need to pass username and password for generating token.
I have written code like this.
string sURL = "https://sampleurl.com/api1/token/Actualusername/Actualpassword";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
wrGETURL.ContentLength = 0;
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
Response.Write(strResult);
I am getting error: No connection could be made because the target machine actively refused it
Is it right way to consume rest api in C#?
This all very much depend on the API's documentation, but to write data to the request body, get the request stream and then write the string to the stream.
again, this depends on what the API you are authenticating with and without knowing which one is guesswork on my part.
string sURL = "https://sampleurl.com/api1/token";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
wrGETURL.Method = "POST";
wrGETURL.ContentType = #"application/json; charset=utf-8";
using (var stream = new StreamWriter(wrGETURL.GetRequestStream()))
{
var bodyContent = new
{
username = "Actualusername",
password = "Actualpassword"
}; // This will need to be changed to an actual class after finding what the specification sheet requires.
var json = JsonConvert.SerializeObject(bodyContent);
stream.Write(json);
}
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
Response.Write(strResult);
Consume API with Basic Authentication in C#
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}

C# HttpWebRequest "Request Header" in JSON POST

I am translating a JSON API into C# Methods, and I encountered a Problem where the JSON RPC API (POST) says
All other methods require the result from authentication ( = sessionId), either per pathparameter
;jsessionid=644AFBF2C1B592B68C6B04938BD26965
or per cookie (RequestHeader)
JSESSIONID=644AFBF2C1B592B68C6B04938BD26965
My current WebRequest Method:
private async static Task<string> SendJsonAndWait(string json, string url, string sessionId) {
string result;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using(StreamWriter streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) {
await streamWriter.WriteAsync(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
Stream responseStream = httpResponse.GetResponseStream();
if(responseStream == null)
throw new Exception("Response Stream was null!");
using(StreamReader streamReader = new StreamReader(responseStream)) {
result = await streamReader.ReadToEndAsync();
}
return result;
}
How do I add the JSESSIONID Parameter to my WebRequest? I am not very familiar with WebRequests, please explain briefly!
Thank you!
Use Cookies.
Your Case would look like this;
private async static Task<string> SendJsonAndWait(string json, string url, string sessionId) {
Uri uri = new Uri(url);
string result;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//Add the JSESSIONID Cookie
if(httpWebRequest.CookieContainer == null)
httpWebRequest.CookieContainer = new CookieContainer();
if(!string.IsNullOrWhiteSpace(sessionId))
httpWebRequest.CookieContainer.Add(new Cookie("JSESSIONID", sessionId, "/", uri.Host));
using(StreamWriter streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) {
await streamWriter.WriteAsync(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
Stream responseStream = httpResponse.GetResponseStream();
if(responseStream == null)
throw new Exception("Response Stream was null!");
using(StreamReader streamReader = new StreamReader(responseStream)) {
result = await streamReader.ReadToEndAsync();
}
return result;
}
You can add the token directly to your URL :
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create($"{url}?jsessionid={sessionId}");
Or in the headers :
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create({url);
httpWebRequest.Headers["JSESSIONID"] = sessionId;

How to upload images using REST API and C#

I am using php REST API and C# to post an image along with access token by using RestSharp, sending image file and access token as parameters but i unable to achieve with this below sample program
private static void postPrescription(string ext, string mime, string token)
{
var restClient = new RestClient("http://api.xxy.in/v1/docsupload");
restClient.AddHandler("application/octet-stream", new RestSharp.Deserializers.JsonDeserializer());
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("client-Identifier", "192.168.1.24");
request.AddHeader("client-Platform", "kiosk");
request.AddHeader("client-Version", "2.00");
request.AddHeader("client-Type", "kiosk");
request.AddHeader("Accept", "application/json");
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("FILE_EXT", ext);
dict.Add("FILE_MIME_TYPE", mime);
byte[] imageBytes;
using (FileStream fs = File.Open(#"C:\Prescriptions\Presc_1_10_2015_17_19_17.jpeg", FileMode.Open))
{
imageBytes = new BinaryReader(fs).ReadBytes((int)fs.Length);
}
string image = Convert.ToBase64String(imageBytes);
dict.Add("IMAGE_DATA", image);
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dict));
request.AddParameter("access_token", token);
request.AddParameter("userfile", data);
var response = restClient.Execute(request);
JavaScriptSerializer json = new JavaScriptSerializer();
Dictionary<string, object> dict1 = json.Deserialize<Dictionary<string, object>>(response.Content);
}
While trying with above snippet i got a response as
"{\"response\":400,\"message\":\"File not supported\"}"
After this I tried using HTTP POST method but not succeeded, i got http response as "{\"response\":401,\"message\":\"You have been logged out to protect your privacy. Please log back in.\"}"
This is my second snippet,
public static void prescriptionPost(string token)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.xxy.in/v1/docsupload");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequestHeaders(httpWebRequest);
httpWebRequest.ContentType = "application/octet-stream";
byte[] imageBytes;
using (FileStream fs = File.Open(#"C:\Prescriptions\Presc_1_10_2015_17_19_17.jpeg", FileMode.Open))
{
imageBytes = new BinaryReader(fs).ReadBytes((int)fs.Length);
}
string image = Convert.ToBase64String(imageBytes);
byte[] data = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(image));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
pres ps = new pres
{
access_token = token,
userfile = image
};
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ps, Newtonsoft.Json.Formatting.Indented);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
StringBuilder output = new StringBuilder();
var result = streamReader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var myobj = serializer.Deserialize<ObtainToken>(result);
}
// example deserializedProduct = Newtonsoft.Json.JsonConvert.DeserializeObject<example>(json);
}
internal class pres
{
public string access_token { get; set; }
public string userfile { get; set; }
}
I dont know whether my snippets are correct or there was a problem exists in RestApi
Can anyone suggest me that how can i achieve this.
using RestSharp;
byte[] imgdata = ImageFileToByteArray(#"D:\SampleIMG.jpg");
RestRequest request = new RestRequest("URL", Method.POST);
request.AddParameter("secret_key", "secret_key_data");
request.AddParameter("Name_Key","Mahesh");
request.AddFile("imageKey", imgdata, "SampleIMG.jpg", "image/jpeg");
RestClient restClient = new RestClient();
IRestResponse response = restClient.Execute(request);

How to send image in HttpClient SendRequestAsync

I am using Windows.Web.Http instead of System and I am trying to send an image.
My sample code:
Dictionary<string, object> requestDictionary;
HttpClient httpClient = new HttpClient();
HttpRequestMessage re = new HttpRequestMessage();
HttpResponseMessage response;
re.Method = HttpMethod.Post;
re.RequestUri = url;
string content_type = "application/json";
string req_data = JsonConvert.SerializeObject(requestDictionary);
re.Content = new HttpStringContent(req_data, UnicodeEncoding.Utf8, content_type);
response = await httpClient.SendRequestAsync(re);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
httpClient.Dispose();
httpClient=null;
In this case my requestDictionary will be some thing like
requestDictionary.Add("Image", filename);
requestDictionary.Add("description", some_description);
Someone please help me to achieve this.
By using .Net 4.5 (or by adding the Microsoft.Net.Http package from NuGet) there is an easier way to do this:
private string Upload(string actionUrl, string paramString, byte[] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "paramter");
formData.Add(bytesContent, "image");
var response = client.PostAsync(actionUrl, formData).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStringAsync().Result;
}
}
If you prefer to use a stream instead of a byte-array you can easily do this, by just using new StreamContent() instead of new ByteArrayContent().

Categories