I am trying to post data to a Unix API, where it first will verify username and password, and then save the data which was sent.
The code I am using as of now is:
string strUrl = string.Format("http://moktrp.com/inf0/?username=fds- Sale003&password=CBA203&type=0&dlr=1&destination={0}&itemCode=1003);
WebRequest request = HttpWebRequest.Create(strUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = (Stream)response.GetResponseStream();
StreamReader readstream = new StreamReader(s);
string datastring = readstream.ReadToEnd();
response.Close();
s.Close();
readstream.Close();
return true;
Related
HttpClient myClient = new HttpClient();
myClient.BaseAddress = new Uri(URL);
Base address already specified on client it's URL.
var encodedObject = JsonConvert.SerializeObject(Obj);
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await myClient.PostAsync("test.php/yourAPI",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var responseContent = response.ToString();
var responsebody = response.Content.ToString();
Stream receiveStream = response.GetResponseStream();
string responseBodyAsText = response.Content.ReadAsStringAsync().Result;
}
Could be a content negotiation issue. Try clearing the Accept header before adding the json media type
myClient.DefaultRequestHeaders.Accept.Clear();
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//...other code removed for brevity.
this code sets the Accept header to "application/json", which tells the server to send data in JSON format.
Reference source: Calling a Web API From a .NET Client in ASP.NET Web API 2
the Method PostAsync has as first argument the complete URI of The API. Therefore, it should be like follow :
HttpResponseMessage response = await myClient.PostAsync("http://bla-bla-bla/test.php/test",new StringContent(encodedObject, System.Text.Encoding.UTF8, "application/json"));
And there is no need to define the BaseAddress.
I am sending a post request from an ASP.NET MVC 2.0 Controller to another site on the same domain using HttpWebRequest. I am sending username and password to logon to the site. That site uses forms authentication. So it sets authentication cookie. But when I get response in HttpWebResponse object, I find cookie neither in cookie container nor inside header (no Cookie or Set-Cookie header found). Let me add some code snippet here used in the MVC controller:
HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = postData.Length;
if (httpRequest.CookieContainer == null)
{
//httpRequest.CookieContainer = new CookieContainer();
}
httpRequest.Headers.Add(HttpRequestHeader.Cookie, "a=b");
var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(postData);
streamWriter.Close();
HttpWebResponse httpResponse = (HttpWebResponse) httpRequest.GetResponse();
string postBody = "";
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream()))
{
postBody = reader.ReadToEnd();
}
return this.Content(postBody);
Please note that I am not using cookie container and cookie header at the same time in HttpWebRequest.
I don't understand what I am missing here to get authentication cookie in web response.
Try to use
request.CookieContainer.Add(new Cookie("a", "b"));
instead of adding cookie as a header.
I'm trying to download a Fusion table programatically using C# only not .NET. I'm having trouble finding a decent API or C# example code to do so. Is that even possible?
HttpWebRequest request = WebRequest.Create(this.url2 + "?sql=SELECT * FROM 'table id'") as HttpWebRequest;
request.Method = "GET";
request.Headers.Add("Authorization", "GoogleLogin auth=" + this.token);
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
return reader.ReadToEnd();
}
What am I doing wrong?
So what I'm trying to do is to login to a website, and then make a POST request. I've tried just making a webbrowser, and simply logging in there, then submitting the POST data with a button. I'm not sure if it isn't working this way because it's not being sent through webbrowser1 or because I'm not submitting the POST data correctly. Here was the code to submit the POST data.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("url");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "postdata";
req.ContentLength = postData.Length;
StreamWriter stOut = new
StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(postData);
stOut.Close();
I also tried just logging in with one button, then with another button, submitting this POST data, but the problem is that it needs the CSRF token inside the POST request. Here is what I had so far.
string formUrl = "loginurl";
string formParams = string.Format("username={0}&password={1}&csrfmiddlewaretoken={2}", "user", "pass", "token");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
What would be the best way of doing this? Thank you!
You can try binding to the "ajax:before" event in jquery to transparently add in a parameter for the CSRF token before sending off. How you would add the CSRF token in is dependent on what web framework you're using.
I have been looking for a way to remove an attachment from Jira using the SOAP Api, but it seems that this is not possible natively, and I would prefer not having to implement a new plugin for Jira, as suggested in the accepted answer to this question, or recompiling the existing plugin to support this as mentioned here.
This answer to the abovementioned question seems to do exactly what I want, but alas, I can't get i to work. The response i get is an error stating that:
XSRF Security Token Missing
JIRA could not complete this action due to a missing form token.
You may have cleared your browser cookies, which could have resulted in the expiry of your current form token. A new form token has been reissued.
As I am using Asp.Net MVC C#, I have used the code from the answer, as is, with only the server url adjusted, as well as with different credentials (a Jira user) and the username/password passed through as request parameters using:
os_username=jirausername&os_password=xxxxxxx
The code I am currently using is as follows:
public void RemoveAttachment(string issueid, string attachmentid)
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
//Compute jira server base url from WS url
string baseUrl = _service.Url.Substring(0, _service.Url.IndexOf("/rpc/"));
//Compute complete attachment url
string attachmenturl = baseUrl + "/secure/DeleteAttachment.jspa?id=" +
issueid + "&deleteAttachmentId=" + attachmentid;
client.Credentials = new System.Net.NetworkCredential("jirausername", "xxxxxxx");
string response = client.DownloadString(attachmenturl);
}
}
I ended up using a method that first requests the deletion confirmation form, then extracts a required token from the form, and finally posts something equivalent to the form content in order to delete the attachment. Code below.
public void RemoveAttachment(string issueid, string attachmentid)
{
//Compute jira server base url from WS url
string baseUrl = _service.Url.Substring(0, _service.Url.IndexOf("/rpc/"));
//Compute complete attachment deletion confirm url
string confirmurl = baseUrl + "/secure/DeleteAttachment!default.jspa?id=" +
issueid + "&deleteAttachmentId=" + attachmentid + "&os_username=jirauser&os_password=xxxxxx";
//Create a cookie container to maintain the xsrf security token cookie.
CookieContainer jiracontainer = new CookieContainer();
//Create a get request for the page containing the delete confirmation.
HttpWebRequest confirmrequest = (HttpWebRequest)WebRequest.Create(confirmurl);
confirmrequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
confirmrequest.CookieContainer = jiracontainer;
//Get the response and the responsestream.
WebResponse confirmdeleteresponse = confirmrequest.GetResponse();
Stream ReceiveStream = confirmdeleteresponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader confirmreader = new StreamReader(ReceiveStream);
// Read the content.
string confirmresponse = confirmreader.ReadToEnd();
//Create a regex to extract the atl/xsrf token from a hidden field. (Might be nicer to read it from a cookie, which should also be possible).
Regex atl_token_matcher = new Regex("<input[^>]*id=\"atl_token\"[^>]*value=\"(?<token>\\S+)\"[^>]*>", RegexOptions.Singleline);
Match token_match = atl_token_matcher.Match(confirmresponse);
if (token_match.Success)
{
//If we found the token get the value.
string token = token_match.Groups["token"].Value;
//Compute attachment delete url.
string deleteurl = baseUrl + "/secure/DeleteAttachment.jspa";
//Construct form data.
string postdata = "atl_token=" + HttpContext.Current.Server.UrlEncode(token) + "&id=" + issueid + "&deleteAttachmentId=" + attachmentid + "&Delete=Delete&os_username=jirauser&os_password=xxxxxx";
//Create a post request for the deletion page.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(deleteurl);
request.KeepAlive = false;
request.CookieContainer = jiracontainer; // Remember to set the cookiecontainer.
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
//Turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(postdata);
//Make sure you specify the proper type.
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
//Send the post.
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
//Get the response.
WebResponse deleteresponse = request.GetResponse();
// Open the responsestream using a StreamReader for easy access.
StreamReader deleteresponsereader = new StreamReader(deleteresponse.GetResponseStream());
// Read the content.
string deleteresponsecontent = deleteresponsereader.ReadToEnd();
// do whatever validation/reporting with the response...
}
else
{
//We couldn't find the atl_token. Throw an error or something...
}
}
Edit:
Same thing works for removing comments. Replace 'attachment' with 'comment' and 'deleteAttachmentId' with 'commentId' and you should be good to go.