I have the following endpoint
#RequestMapping("missedcall")
fun missedCall(#RequestParam("v") encryptedValue : String, model:
ModelMap): String {
//decrypt encryptedValue here
}
When I execute this endpoint with "http://myurl.com/missedcall?v=this+is+my+encrypted+string", encryptedValue initialized as "this is my encrypted string". I actually want the pluses as they are part of the encryption and I can't decrypt the string without them.
The work around would be URL encode the string back to restore pluses and other special characters, BUT is there a cleaner way? Maybe disabling URL decoding for this particular endpoint?
Note: I can't pass this param in body, it has to be part of the query string. Also this is written in Kotlin, but I am 100% sure Java has similar issues, so don't feel discouraged by Kotlin :).
Any web framework will decrypt the query path for you, as that's expected behavior. If that's not what you want, you will have to define a method argument of type HttpServletRequest and parse the query yourself using HttpServletRequest.getQueryString().
Thanks to #SeanPatrickFloyd, implemented it as
#RequestMapping("missedcall")
fun missedCall(request: HttpServletRequest, model: ModelMap): String {
val encodedValue = request.queryString.split("=")[1]
//decrypt encryptedValue here
}
Related
How to send a boolean value or an integer in http request body in dart? The documentation says that I can only send string, list or a Map. How to make it work for boolean or integer in Dart?
Try this approach which I use in my projects
void apiPost(){
var body = jsonEncode(
{
"string":"test",
"bool":true,
"int":1
});
http.post("url here",body: body,headers: {"Content-Type": "application/json"}).then((response) {
Map map = json.decode(response.body);
});
}
As you saw in the documentation, you can only send those three things: a byte array, a string or a map of string to string. In fact, in the end, you are just sending a byte array. The other options get converted to bytes before sending.
A string is converted to bytes by transforming it into bytes using utf-8 (or some other encoding specified by the content-type header).
A map of string to string is encoded to first as x-www-form-urlencoded and then to bytes. That encoding can, of course, only encode strings.
So the answer to your question really depends on where/how the server expects to receive the fields. If it's expecting them in a form, then it's your responsibility to convert, say, a boolean into whatever string the server expects. Maybe that's 'true'/'false' or '1'/'0' or something else. Make your map like this:
int someInt;
bool someBool;
var formData = <String, String>{
'an_int_value' : someInt.toString(),
'a_bool_value' : someBool.toString(), // assuming 'true'/'false' is OK
};
Also consider the possibility that your server requires a completely different encoding, like JSON. Then you would convert your map to JSON, then pass that as a string, setting the content-type appropriately.
I want to create an HttpPost controller method which takes a string which may include spaces or single quotes. The code I have now looks like:
[HttpPost]
[Route("ValidateExpression")]
public bool ValidateExpression([FromBody] string testExpression )
{
// ...
}
and I post to it via JS (Angular) like:
$http.post(myRootUrl +'ValidateExpression', "'token1' || 'token2'");
I can walk through the JS and see that the test expression is what I expect it to be, and it also looks fine in the body of the outgoing post (as seen in Fiddler & Firebug). But when I breakpoint in the first line of ValidateExpression on the server side, testExpression has been truncated to the first space, and stripped of quotes, so what I receive is token1.
How can I avoid this unwanted transformation?
I guess that I could create a model to wrap a single string, and send my string as field value in a JSON object matching the model...or I could do some escaping on the string, but the first seems ugly/unnecessary and the second seems like I'd be trying to hack around behaviour I don't really understand.
You need to pass in JSON object with key equal to that of parameter name.
// POST api/values
public string Post(string value) {
return value;
}
$.post('/api/values', { value: 'Dave' });
Alternatively, you can satisfy Web API's encoding requirement these ways:
$.post('api/values', "=" + value);
or
$.post('api/values', { '': value });
More information here: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
Edit:
Also, note that angualrjs http.post and jquery.post behaves differently:
The difference is in how jQuery and AngularJS serialize and transmit
the data. Fundamentally, the problem lies with your server language of
choice being unable to understand AngularJS’s transmission
natively—that’s a darn shame because AngularJS is certainly not doing
anything wrong. By default, jQuery transmits data using Content-Type:
x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization.
AngularJS, however, transmits data using Content-Type:
application/json and { "foo": "bar", "baz": "moe" } JSON
serialization, which unfortunately some Web server languages—notably
PHP—do not unserialize natively.
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I'm using Spring 3.1 and I have a handler that should return a String value.
Here's how my handler looks like:
#RequestMapping(value = TEST_HANDLER_PATH, method = RequestMethod.POST)
public ResponseEntity<String> handleTest(HttpServletRequest request,
#RequestParam("parma1") String param) throws Exception {
String ret = ...
...
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/plain;charset=utf-8");
return new ResponseEntity<String>(ret, headers, HttpStatus.CREATED);
}
I also tried annotating method with #ResponseBody with return ret; at the end.
In both cases, when I hit the service, I get extra quotes around String value (e.g. "This is a test").
I'm guessing this is due to message conversion. That's why I tried defining Content-Type header, to hit StringHttpMessageConverter explicitly, to no avail.
Had the same problem.
Just make sure you register a org.springframework.http.converter.StringHttpMessageConverter as well as your Jackson one so that Strings are treated literally and not attempted to be converted to JSON (with extra quotes).
Just instantiate with default constructor or constructor with your preferred Charset. The media types should be set for you with the standard internal defaults. If you're configuring via code extending WebMvcConfigurerAdapter then you just add the converters in the configureMessageConverters(List<HttpMessageConverter<?>> converters) method.
In my case, I had over-engineered =)
Had introduced a converter for bean's toString Operations like this:
class SerializableToString implements Converter<Serializable, String>
restricting that (only to my beans), resolved the issue X)
Note: debugging with a breakpoint # org.springframework.core.convert.support.GenericConversionService.getConverter helped.
In a related scenario, I had an IntegrationFlow for a GET that incorrectly requested a transform. Basically the target service would receive the #PathVariable as a quote escaped string
return IntegrationFlows.from("getThing")
.transform(Transformers.toJson())
.handle(
The .transform(Transformers.toJson()) was forcing the strings to be escaped in the URI, so simply removing it - it shouldn't have been there - fixed the issue.
Turns out there was a JSON message converter registered in one of the imports.
I am trying to insert a .NET serialized JSON document to CouchBase but get gibberish with non-English characters.
I've tried to put:
name = " الفورية مترجم نصوص مجاني إلى "
But I get:
"name": " ״§„ˆ״±״© …״×״±״¬… †״µˆ״µ …״¬״§† ״¥„‰ ",
When viewing it in CouchBase administration page.
Any solution?
I am using ASP.NET 4.5 and latest CouchBase API with CouchBase 2.0 beta.
Also noted on http://www.couchbase.com/forums/thread/gibrish-non-english-characters-using-c-client-and-coucbase-2-0-beta, but copied here for reference:
Hi Idanm
The .NET client stores strings using UTF-8. Are you seeing the data coming out of the client correctly, or are the mixed up strings in the admin console?
Also, you can try the new extension methods that use Newtonsoft.JSON for Json serialization. In the .NET Couchbase Client Beta, you'll find Couchbase.Extensions with the following class:
public static class CouchbaseClientExtensions
{
public static bool StoreJson(this CouchbaseClient client, StoreMode storeMode, string key, object value)
{
var json = JsonConvert.SerializeObject(value);
return client.Store(storeMode, key, json);
}
public static T GetJson<T>(this CouchbaseClient client, string key) where T : class
{
var json = client.Get<string>(key);
return json == null ? null : JsonConvert.DeserializeObject<T>(json);
}
}
It seems possible that the Encoding.Default.GetBytes in the extensions you're using might be at fault here...
Although I'm not familiar with the Couchbase storage system, you're definitely running into a text encoding issue. I'd check that your JSON serializer is serializing to UTF-8 encoding, as well as ensuring that you're specifying UTF-8 encoding on the Couchbase side. Check their APIs and storage types to ensure that they are UTF-8 based.
Why does my action method only bind the first word of a string I pass into it using a query string?
For example, in jquery, I build a queryString from the results of an ajax call:
success: return(resultData){
var queryString = "?ok=true&message=" + resultData.message;
}
Then I try to load a view into a dialog by calling a controller and passing the queryString
$dialogHandle.load("/Account/RegisterStatus" + queryString, function() { ... });
At this point the queryString correctly hold an entire message. However if I break in my controller:
public ActionResult RegisterStatus(bool ok, string message)
{
//break here
}
I notice that ok binds correctly but message only contains the first word of the error message passed in.
How can I pass a sentence as one string parameter?
Is there a better way to do this, without query string?
EDIT: hmm now that I think about it does make sense since urls cant have space but then how do I accomplish this... is there a specific word delimiter in the default model binder?
It's all about URL escaping: escape("It's me!") // result: It%27s%20me%21
Do that around your resultData.Message and it should work better. For debugging purposes, use Fiddler2 or some Web Inspector to see what request is being send. This is really valuable when you are debugging AJAX...
And of course, do the reverse in C#: HttpUtility.UrDecode Method (String)