spring mvc handling multiple query params as String - spring-mvc

my query paramS is x-goog-one=something&x-goog-two=something_else&.......
i have this as a string format its like a very long query param String
do we have anything like #requestParams to process the queryParamS in one param insted of:
#Component
#FeignClient(name = "fileUpload", url = FileUploadSao.GMS)
public interface FileUploadSao {
#PutMapping(value = "/{fileName}", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> uploadFile(#PathVariable("fileName") String filename,
#RequestParam("X-Goog-Algorithm") String xGoogAlgorithm,
#RequestParam("X-Goog-Credential") String credentials,
#RequestParam("X-Goog-Date") String date,
#RequestParam("X-Goog-Expires") String expires,
#RequestParam("X-Goog-SignedHeaders") String signedHeaders,
byte[] imageBinary);
}
Request params hangling in spring mvc,openFeign , I want to process all my query params in one String referense

Related

Retrofit POST request sending email field with %40 instead of #

I am trying to figure out a way to stop Retrofit from encoding the email address that I pass to make a POST request. Here is my POST interface
#POST("/security/oauth/token")
#FormUrlEncoded
void getAccessToken(#Field("client_id") String clientId,
#Field("client_secret") String clientSecret,
#Field("username") String username,
#Field("password") String password,
#Field("grant_type") String grantType, Callback<AccessToken> cb);
When I make the request, Retrofit sends these fields as
client_id=test&client_secret=cajcckkcaaa&username=androidtest12%40gmail.com&password=Password23&grant_type=password
The culprit here is the email address, which is being changed from androidtest12#gmail.com to androidtest12%40gmail.com causing server error.
Thanks in advance for help.
You need to set encodeValue = false for your username field for this to work because it is being encoded. They have this documented over at the Retrofit Javadoc. An example is below using your data.
#POST("/security/oauth/token")
#FormUrlEncoded
void getAccessToken(#Field("client_id") String clientId,
#Field("client_secret") String clientSecret,
#Field(encodeValue = false, value = "username") String username,
#Field("password") String password,
#Field("grant_type") String grantType, Callback<AccessToken> cb);
For Retrofit 2 you should use #Query with encoded = true like this:
public interface ValidateEmailApi {
#GET("/api/email")
Call<Void> validateEmail(#Query(encoded = true, value = "email") #NonNull String email);
}

Write json String directly in SpringMVC

In my spring-mvc application, the client requests with a key and I lookup the associated value in Couchbase. From Couchbase I get a json object as a String, as my application doesn't need to do anything with it I just want this to be written out.
But Spring sees that I want to write a String, and passes it to jackson which then writes it as a json string - adding in quotation marks and escaping the internals.
Simplest example:
#RequestMapping(value = "/thing", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public DeferredResult<String> getThing() {
final DeferredResult<String> result = new DeferredResult<>();
// in future
result.setResult("{}");
return result;
}
Returns: "{}"
I'm thinking of making a serialised json wrapper and a custom serialiser for jackson to just output it's contents.
I think you could use org.springframework.http.ResponseEntity
#RequestMapping(value = "/example", headers = "Accept=application/json")
#ResponseBody
#Transactional
public ResponseEntity<String> example(#RequestParam(value = "documentId", required = true) Integer documentId) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
SomeDTO result = SomeDTO.findDocument(documentId);
if (result == null) {
return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(result.toJson(), headers,HttpStatus.OK);
}
beside, you could use Flexjson to tranfer Oject to Json String.
I added the StringHttpMessageConverter with application/json as a supportedMediaType:
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "application/json" />
</bean>
</mvc:message-converters>
This did get the String responses output as-is.

how can return json using response.senderror

In my app,I use springMVC and tomcat,my controller return object,but when something wrong,I only want return some string message with content tye json,so I use response.error, but it not work,the return is a html.
my controller:
#RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody UserBean login(#PathVariable String id,#PathVariable("name") String userName,
#RequestHeader(value = "User-Agent") String user_agen,
#CookieValue(required = false) Cookie userId,
HttpServletRequest request,HttpServletResponse response,#RequestBody UserBean entity
) throws IOException {
System.out.println("dsdsd");
System.out.print(userName);
response.setContentType( MediaType.APPLICATION_JSON_VALUE);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "somethind wrong");
return null;
According to the Javadoc for the HttpServletReponse#sendError method:
Sends an error response to the client using the specified status. The
server defaults to creating the response to look like an
HTML-formatted server error page containing the specified message,
setting the content type to "text/html", leaving cookies and other
headers unmodified...
So sendError will generate an HTML error page using the message that you supplied and will override the content type to text/html.
Since the client end is expecting a JSON response, you may be better to manually set the response code and the message yourself using fields on your UserBean - assuming it can support it. That will then be serialized to a JSON response that your clientside Javascript can evaluate.
#RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody UserBean login(#PathVariable String id,#PathVariable("name") String userName,
#RequestHeader(value = "User-Agent") String user_agen,
#CookieValue(required = false) Cookie userId,
HttpServletRequest request,HttpServletResponse response,#RequestBody UserBean entity
) throws IOException {
System.out.println("dsdsd");
System.out.print(userName);
response.setContentType( MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
UserBean userBean = new UserBean();
userBean.setError("something wrong"); // For the message
return userBean;
There is also the option of using the Tomcat property org.apache.coyote. USE_CUSTOM_STATUS_MSG_IN_HEADER which will place the message into a custom response header. See this post and the Tomcat docs for more info.

How to pass a JSON string variable from ASP.NET to other applications?

In my webapplication I need to pass a string variable using JSON. But it doesn't work... My code is:
string Token=builder.ToString();
var userdetails = {"token": Token};
Response.Write(userdetails);
You could use a JSON serializer, such as the JavaScriptSerializer class:
string Token = builder.ToString();
var userDetails = new { token = Token };
string json = new JavaScriptSerializer().Serialize(userDetails);
Response.ContentType = "application/json";
Response.Write(json);
The generated output will look like this:
{"token":"some token value"}

how to return list in asp.net to a json post

So in my web service i get the data from textboxes search it in database and create letter objects.Then add those objects to a list.my question is how do i return the list to my web page and create divs. for example if service finds 5 letters how i do i return them and create 5 different divs with their data.Thanks in advance
public Letter(string lid, string companyname, string personname, string email, string fax, string phone, string industryname, string teamname, string sender, string statusname, string description, string date)
{
LID = lid;
CompanyName = companyname;
PersonName = personname;
Email = email;
Fax = fax;
Phone = phone;
IndustryName = industryname;
TeamName = teamname;
Sender = sender;
StatusName = statusname;
Description = description;
Date = date;
}
You just need to decorate your web services with ScriptService attribute and it will return response in raw json format. For more info check it out here and you also want to check out this.
Once you get Json response, you can do something like this to render the output as per your requirement. It's not exactly what you're looking for but it will give you an idea how to proceed further.
In .net 3.5 you can create json by using the System.Web.Script.Serialization.JavaScriptSerializer otherwise you have to do it manually or by a 3rd party component.

Resources