get response header of request from HttpWebResponse - c#

i am trying to implement my code as per these requirement. That is saying The response to this POST will include a header named LOCATION, which is a URL with parameters indicating where to upload the file via a second POST.. For request i have did below code but i stuck at point where i need to get LOCATION from header. For request i did below code and i want to get LOCATION from Header of response.
string responseStr = "";
HttpStatusCode statusCode;
WebRequest request = WebRequest.Create(URL);
//request.Credentials = new NetworkCredential(bigApiUserID, BigApiKey);
request.Method = "POST";
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(stringOrder);
request.Headers.Add("Authentication", token);
request.ContentType = "application/json";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode;
response.Headers
if (Convert.ToString(response.StatusCode) == "OK")
{
Stream responseStream = response.GetResponseStream();
responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}

Related

API call going in timeout from windows forms working fine from Postman

I am trying to call API from windows forms its going in timeout. but its working fine from POSTMAN app.
I am using below code for calling web API from windows app.
public string ReadXMLResponse(string strrequestxml, string strTallyServer1)
{
string URL = strTallyServer1;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpWebRequest.Accept = "application/xml";
myHttpWebRequest.ContentType = "application/xml";
myHttpWebRequest.Timeout = 60000;
string method = "POST";
myHttpWebRequest.Method = method;
if (method == "POST")
{
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
streamWriter.Write(strrequestxml);
streamWriter.Flush();
}
}
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
var streamRead = streamReader.ReadToEnd().Trim();
return streamRead;
}
return "";
}
I had the same code and the same problem. It was driving me crazy till I found something on one of Microsoft blogs. Tried to google the original page but I couldn't find it.
WebRequest request = WebRequest.Create("URL");
request.Method = "POST";
var postData = string.Format(dataFormnat, Uri.EscapeDataString(data.Serialize()));
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

The remote server returned an error: (403) Forbidden.. in google short url

public string GetShortURL(string longUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.googleapis.com/urlshortener/v1/url?key=My_API_Key");
request.Method = "POST";
request.ContentType = "application/json";
string requestData = string.Format(#"{{""longUrl"": ""{0}""}}", longUrl);
byte[] requestRawData = Encoding.ASCII.GetBytes(requestData);
request.ContentLength = requestRawData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestRawData, 0, requestRawData.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
I am trying to create short url by passing my original url string but it is giving an exception

SOAP API in salesforce for login

I wants to get session id from salesforces using soap API for login. Below is my code for request but i am getting salesforce login page as html response.
Any thoughts ?
public static string Authentication()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SalesForce_authenticationAPI);
request.ContentType = "text/xml; charset=UTF-8";
request.Headers.Add("SOAPAction", #"\");
request.Method = "POST";
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(CreateSoapEnvelope().InnerXml);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
//return only sessionId
return responseStr;
}
return null;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/' xmlns:x='http://www.w3.org/2001/XMLSchema-instance' xmlns='urn:partner.soap.sforce.com'><s:Body><login><username>xyz#account.com</username><password>*********</password></login></s:Body></s:Envelope>");
return soapEnvelop;
}
Rather than doing the SOAP stuff by hand, check out the Force.com-Toolkit-for-NET.
I don't have a .Net sample but here is a Scala example that uses the Salesforce SOAP API to login: https://github.com/jamesward/force-login

(400) Bad Request, can't get response (Custom minecraft launcher)

I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data

How make a post to URL and get the response

I try to post an XML file to the url and get the response back. I have this code to post. I am not really sure how to check if it is posting correctly and how to get the response.
WebRequest req = null;
WebResponse rsp = null;
// try
// {
string fileName = #"C:\ApplicantApproved.xml";
string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml; encoding='utf-8'";
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();
I think I should have response in rsp but I am not seeing anything usufull on it.
Please try following.
WebRequest req = null;
string fileName = #"C:\ApplicantApproved.xml";
string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml; encoding='utf-8'";
// Write the XML text into the stream
byte[] byteArray = Encoding.UTF8.GetBytes(this.GetTextFromXMLFile(fileName));
// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = req.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = req.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
try
req.ContentType = "application/xml";

Categories