HTTP request parameters are not available by request.getAttribute() - servlets

I am sending an url parameter to servlet using the following jQuery piece:
$.getJSON("http://localhost:8080/JsoupPrj/JasonGen?url=" + url, function(data) {
$("#content").html(data);
});
On the server side, the servlet gets the parameter, for that I coded as below:
String url = (String) request.getAttribute("url");
But it is not working, can you tell me where I am doing wrong? I believe I am not passing the parameter properly to the servlet. The servlet triggers each time through the JavaScript, but it is not seeing the parameters passed from the browser.

Here,
String url = (String) request.getAttribute("url");
you're trying to get a request parameter as a request attribute instead of as a request parameter. This will obviously not do what you want.
You need to get a request parameter as a request parameter, not as a request attribute.
String url = request.getParameter("url");
Unrelated to the concrete problem: you don't seem to be URL-encoding the parameter at all before sending. This will possibly cause other problems, unrelated to this one, when the url contains special characters. Look at the JS encodeURIComponent() function, or the data argument of the $.getJSON() function. See for more hints also How to use Servlets and Ajax?

Related

Tracing an HTTP request in Go in a one structured log line

I have learned you can "decorate" the HTTP transport so that you can details of the request, however I can't quite figure out how you log the URL in the same line.
https://play.golang.org/p/g-ypQN9ceGa
results in
INFO[0000] Client request dns_start_ms=0 first_byte_ms=590 response_code=200 total_ms=590 url=
INFO[0000] 200
I'm perpetually confused if I should be using https://golang.org/pkg/context/#WithValue to pass around the context in a struct, especially in light where https://blog.golang.org/context-and-structs concludes with pass context.Context in as an argument.
Go through the behaviour of how the request is constructed in request.go from net/http. You see that the RequestURI field is never set there. Quoting from same reference,
Usually the URL field should be used instead.
It is an error to set this field in an HTTP client request
So, I would suggest you to use request.URL instead.
It is a parsed from the request uri. It should have the data you need.
You can construct the output as following:
f := log.Fields{
"url": fmt.Sprintf("%s %s%s", r.Method, r.URL.Host, r.URL.Path),
}
Also, in my experience, it is far more easier to use context.WithValue and pass the context as an argument.
Replace r.RequestURI by r.URL.String() in your code to log the full, valid URL (https://golang.org/pkg/net/url/#URL.String). RequestURI is empty on the client side (https://golang.org/pkg/net/http/#Request), as the output from your code is showing.
I don't see how context.Context relates to your question, but I believe https://blog.golang.org/context-and-structs is considered "best practice".

Elm - retrieving string via get request

I am trying to make a get request to retrieve a string
When I use
retrieve : Task.Task Http.Error String
retrieve = getString "http://api.endpoint.com"
everything works fine.
On the other hand if I use
retrieve : Task.Task Http.Error String
retrieve = get Json.Decode.string "http://api.endpoint.com"
the http request gets done, but the chained tasks are not executed.
My question is: what is the difference between the two approaches above? Am I doing something wrong with the second one? How to debug it?
getString returns the response of the get request as a String. get take a JSON decoder and runs that over the response of the get request. So if you provide Json.Decode.string, it will expect the response to be have a Json encoded string in it. So it expects extra double quotes in the response.
If your http request fails the best way to debug is to look at what kind of error you get. In this case you'll probably get an UnexpectedPayload because the request succeeds, but the decoder fails.

Http patch issue using fiddler

[HttpPatch]
public HttpResponseMessage UpdateDividendInformation([FromBody]BEDividendInformationRequest bedividendInformationRequest, Delta<BEAccountDividendSetup> beAccountDividendSetup)
When I am calling from fiddler using http patch its showing:
"Can't bind multiple parameters error" .
Please anyone help in this. I am using Delta class for tracking changed entities. So how to send values through fiddler.
Basically, There is at most 1 parameter allowed from body because the request content maybe read only once.
In your action, you mark the first parameter [FromBody], meantime, Delta<T> is decorated with [NonValidatingParameterBinding] attribute in OData Web API, That's a parameter from body. So, you have two parameters which will bind from body. Therefore, it's obvious that you got the such error message.
However, the error message should contain the parameter names. Do you omit it?

How to get # value in query string from a URL coming from an API, not the current request

I get a returned url from using facebook api:
http://www.example.com/#access_token=BAAGgUj7asdasdasdasda4z3cBAFD5ZAyTOMIxtBpjIHsNwLfZC6L9gZAIdSIt3bKP96rg7yAlplMBDA9ZCndAKS9a7m4oRmRmJAxSdCueefweWJrlq3vQv3XaGqTOLofEMjJIVNCYZD&expires_in=0
But i am not sure how to get the token value? As its not in query string or Request.url
Any help?
You can't, assuming this is passed in on the current request, as anything after the # is never sent to the server.
You can capture it in JavaScript and use AJAX to send it to the server, but this will be on a different request.
If you mean you have this URL not from the current request, you can use the Uri class to parse a full URL and get the fragment:
var fragment = new Uri(theUri).Fragment;
var token = fragment.Split(new [] {'&','='}, StringSplitOptions.None)[1];
You can use HttpUtility.ParseQueryString to parse the URL then you can get the value by name e.g.
NameValueCollection query = HttpUtility.ParseQueryString(querystring);
string token = query["token"];
Check this Retrieving Anchor Link In URL for ASP.Net
you cannot get it from the server side, you will need to take if from client side first then pass it to the server in a hidden field or something similar
You have to look for "%23", because "#" is url-encoded to "%23"
reference:
http://www.w3schools.com/tags/ref_urlencode.asp
But you have to know also, that anchors are not available on server side!

How do we pass parameters when doing HTTP Post?

I am working on an app where we have to pass specific web api parameters to a web app using HTTP POST.
eg:
apimethod name
parameter1 value
parameter2 value
So do I use a string or URLEncodedPostData to send that data?
It would be good if u help me with a code eg.
I am using something like this but it doesnt post the data to the server.
Though the response code is ok/200 and I also get get a parsed html response when i read the httpresponse input stream. But the code doesnt post anything. So unable to get the expected response.
_postData.append("method", "session.getToken");
_postData.append( "developerKey", "value");
_postData.append( "clientID", "value");
_httpConnection = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
String encodedData = _postData.toString();
_httpConnection.setRequestMethod(HttpConnection.POST);
_httpConnection.setRequestProperty("User-Agent", "BlackBerry/3.2.1");
_httpConnection.setRequestProperty("Content-Language", "en-US");
_httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
_httpConnection.setRequestProperty("Content-Length",(new Integer(encodedData.length())).toString());
os = _httpConnection.openOutputStream();
os.write(requeststring.getBytes());`
The code you posted above looks correct - although you'll want to do a few more things (maybe you did this already but didn't include it in your code):
Close the outputstream once you've written all the bytes to it
Call getResponseCode() on the connection so that it actually sends the request
POSTed parameters are usually sent in the response BODY, which means URL-encoding them is inappropriate. Quote from the HTTP/1.1 protocol:
Note: The "multipart/form-data" type has been specifically defined
for carrying form data suitable for processing via the POST
request method, as described in RFC 1867 [15].
The post method allows you to use pretty arbitrary message bodies — so it is whatever format the server wants.

Resources