I have an oddity I hope someone can help with, I have an application which is uploading a reasonably long string as a post parameter, I know the web request is right because it works fine with PHP.
With Rails 4 though it seems to just chop off the string at the same point every time, yet I can't find any documentation that indicates this is normal behavior i'm assigning it like so:
mystring= params[:post_xml]
if I do the following:
mystring = request.body.read
It works fine!
Any ideas?
EDIT For clarity here's my C# request code its on port 3001 as thats the test port for rails
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://mydomain.com:3001/api/new");
ASCIIEncoding encoding = new ASCIIEncoding();
var textFromDoc = Globals.ThisAddIn.Application.ActiveDocument.Content.Text;
// string postData = "content=" + textFromDoc;
//byte[] data = encoding.GetBytes(postData);
byte[] data = Encoding.UTF8.GetBytes(textFromDoc);
httpWReq.Method = "POST";
httpWReq.ContentType = "text/xml; encoding='utf-8'";
//"application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
System.Windows.Forms.MessageBox.Show(responseString);
}
catch (System.Exception excep)
{
System.Windows.Forms.MessageBox.Show(excep.Message);
}
ActionController::StrongParameters#params is very different from ActionDispatch::Request#body. These two methods serve different purposes.
Check out Chapter 4: Parameters in the Action Controller Overview to learn more.
Related
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'm using the DotNetOpenAuth framework which has been great to get up to speed with consuming data.
I'm using it to talk to LinkedIn and am having trouble figuring out the correct approach to posting/sharing information to the site. Here is the reference I am using - http://developer.linkedin.com/documents/share-api
When I execute the below code I always get the below error responses;
Error occurred while sending a direct message or getting the response.
The remote server returned an error: (400) Bad Request.
I am using Oauth v1.0a.
Here is my code;
try
{
HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><share><comment>83% of employers will use social media to hire: 78% LinkedIn, 55% Facebook, 45% Twitter [SF Biz Times] http://bit.ly/cCpeOD</comment>";
xml += "<content><title>Survey: Social networks top hiring tool - San Francisco Business Times</title>";
xml += "<submitted-url>http://sanfrancisco.bizjournals.com/sanfrancisco/stories/2010/06/28/daily34.html</submitted-url>";
xml += "<submitted-image-url>http://images.bizjournals.com/travel/cityscapes/thumbs/sm_sanfrancisco.jpg</submitted-image-url>";
xml += "</content><visibility><code>anyone</code></visibility></share>";
var multiparts = new List<MultipartPostPart>();
MultipartPostPart part = MultipartPostPart.CreateFormPart("body", xml);
part.PartHeaders[HttpRequestHeader.ContentType] = "application/xml";
multiparts.Add(part);
var resourceEndpoint = new MessageReceivingEndpoint("http://api.linkedin.com/v1/people/~/shares", resourceHttpMethod);
HttpWebRequest request = consumer.PrepareAuthorizedRequest(resourceEndpoint, accessToken, multiparts);
request.ServicePoint.Expect100Continue = false;
IncomingWebResponse response = consumer.Channel.WebRequestHandler.GetResponse(request);
this.resultsBox.Text = response.GetResponseReader().ReadToEnd();
}
catch (Exception ex)
{
}
Thanks
Forgot to write back on this, talking to someone from a vintage google newsgroup I got the direction I needed but wanted to verify the solution before posting.
The big thing I was screwing up on was adding the multipart data prior to sending the request data as opposed to constructing the request myself and writing the new content to the stream.
I'm new to using OAuth and REST so I don't know all the ins and outs, suffice to say I've validated this code against both the LinkedIn and Twitter REST APIs.
Here is the new CODE;
try
{
Encoding encoder = Encoding.ASCII;
HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
byte[] bytes = encoder.GetBytes(xd.OuterXml.ToString());
var resourceEndpoint = new MessageReceivingEndpoint(ResourceURL, resourceHttpMethod);
HttpWebRequest request = _consumer.PrepareAuthorizedRequest(resourceEndpoint, _manager.AccessToken);
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "application/xml";
using (System.IO.Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
IncomingWebResponse response = _consumer.Channel.WebRequestHandler.GetResponse(request);
ret = true;
}
catch (Exception ex)
{
_Logger.Error(OpenLogger.FormatException(ex));
}
I am making a web-application in ASP.NET. I have used oauth to get profile fields of a user. I need the names of the companies followed by the user, but the problem is that the default value is set to 20. so, if the user is following more than 20 companies i am not able to get it. Please tell me how can i modify the start and count values. Iv used this url to make the call http://api.linkedin.com/v1/people/~:(following:(people,companies,industries,news-sources),educations).. Please help asap..
var requestHeader = GetUserProfileAuthorizationHeader();
var queryString = CreateQueryString();
var request = WebRequest.Create(RequestProfileUrl + queryString);
request.Headers.Add("Authorization", requestHeader.ToString());
request.Method = HttpMethod.Get;
try
{
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
Here public static string RequestProfileUrl = "http://api.linkedin.com/v1/people/~:(following:(companies:(id,name,size,industry),industries))"; And the method CreateQueryString() does this queryString = "?format=xml"; whenever i try to add something like queryString = "?format=xml&start=0&count=40"; it gives error dispite the number of companies followed being more than 60.. maybe i need to pass the query parameters in between the RequestProfileUrl i.e near the company somehow..
Did you tried adding ?start=x&count=y to the url?
Probably if you're getting an error when you add query parameters to the URL, you're not adding those parameters in the way that your OAuth library expects them to be added. You need to figure out how to add the parameters so they're added to the signature generation process or your signature will be invalid and you'll get a 401 error back from the server.
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.
I am trying to generate the OData Proxy for the service : http://services.odata.org/Northwind/Northwind.svc/$metadata
I am using System.Data.Services.Design.EntityClassGenerator for generating the OData proxy.
When I instantiate the EntityClassGenerator and call GenerateCode the output has no errors. But there is no code in the generated proxy code.
The same code works for my own service. But when I point it to any external service the EntityClassGenerator is not working.
Here is the code :
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(metadataEndpoint);
webRequest.Method = "GET";
webRequest.ContentType = "text/xml;encoding='utf-8";
webRequest.Proxy = (proxy != null) ? proxy : WebRequest.DefaultWebProxy;
using (WebResponse response = webRequest.GetResponse())
{
string xml = string.Empty;
XmlReaderSettings settings = new XmlReaderSettings();
using (TextReader reader = new StreamReader(response.GetResponseStream()))
{
xml = reader.ReadToEnd();
using (XmlTextReader sourceReader = new XmlTextReader(reader))
{
using (StringWriter targetWriter = new StringWriter())
{
// Generate the OData End point proxy.
EntityClassGenerator entityGenerator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode);
entityGenerator.OnPropertyGenerated += new EventHandler<PropertyGeneratedEventArgs>(entityGenerator_OnPropertyGenerated);
IList<System.Data.Metadata.Edm.EdmSchemaError> errors = entityGenerator.GenerateCode(sourceReader, targetWriter, namespacename);
entityGenerator.OnPropertyGenerated -= new EventHandler<PropertyGeneratedEventArgs>(entityGenerator_OnPropertyGenerated);
odataProxyCode = targetWriter.ToString();
}
}
}
}
I found the code in the question to be a useful starting point for doing exactly what the OP was asking. So even though the OP doesn't accept answers, I'll describe the changes I made to get it to work in case it is useful to someone else.
Removed the xml = reader.ReadToEnd(); call. I assume that was for debugging purposes to look at the response from the web request, but it had the result of "emptying" the reader object of the response. That meant that there was nothing left in the reader for the GenerateCode call.
The important one: Changed the use of EntityClassGenerator to System.Data.Services.Design.EntityClassGenerator. In the code below, I included the entire name space for clarity and specificity. Based on the code in the question, it appears the OP was probably using System.Data.Entity.Design.EntityClassGenerator. I used .NET Reflector to examine datasvcutil.exe, which is a command-line utility that can generate the proxy classes. I saw that it referenced the generator in that other name space.
For figuring out the problems, I dumped the errors from the GenerateCode call. One could examine them in the debugger, but some kind of automated checking of them would be needed regardless.
Here is what I ended up with:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.
Create("http://services.odata.org/Northwind/Northwind.svc/$metadata");
webRequest.Method = "GET";
webRequest.ContentType = "text/xml;encoding='utf-8";
webRequest.Proxy = WebRequest.DefaultWebProxy;
using (WebResponse response = webRequest.GetResponse())
{
using (TextReader reader = new StreamReader(response.GetResponseStream()))
{
using (XmlTextReader sourceReader = new XmlTextReader(reader))
{
using (StringWriter targetWriter = new StringWriter())
{
// Generate the OData End point proxy.
System.Data.Services.Design.EntityClassGenerator entityGenerator =
new System.Data.Services.Design.EntityClassGenerator(
System.Data.Services.Design.LanguageOption.GenerateCSharpCode);
IList<System.Data.Metadata.Edm.EdmSchemaError> errors =
entityGenerator.GenerateCode(sourceReader, targetWriter,
"My.Model.Entities");
foreach (System.Data.Metadata.Edm.EdmSchemaError error in errors)
Console.WriteLine("{0}: {1}", error.Severity.ToString(), error.Message);
string odataProxyCode = targetWriter.ToString();
}
}
}
}