I'm having a encoding issue when I send a AJAX request to an API Endpoint.
I have this Endpoint in the code below using Java Spring:
#Autowired
ApiKeyRepository apiKeyRepository;
#RequestMapping(value= "/weather/{cityName}/{fuCity}/now", method = {RequestMethod.GET}, produces="application/json" )
public ResponseEntity<Weather> getWeatherNowByCityName(#PathVariable(value = "cityName") String cityName, #PathVariable(value = "fuCity") State fuCity) throws JSONException, ParseException, java.text.ParseException {
String newCityName = cityName.toLowerCase();
try {
newCityName = URLDecoder.decode(newCityName , "UTF-8").replace(" ", "%20");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String weatherEndpoint = "/api/v1/locale/city?name=" + newCityName + "&state=" + fuCity.toString();
String appToken = apiKeyRepository.getByservice("climaTempo");
URL weatherDomain = new URL("http://apiadvisor.climatempo.com.br" + weatherEndpoint + "&token=" + appToken);
/// From here I send a JSON Request to the 'weatherDomain' to get the Weather from the city and her state that I get from the EndPoint Parameters
}
And I send this jQuery Ajax request to the Endpoint:
var uf = $("#colWeather #selectState").val();
var city = $("#colWeather #selectCity").val();
$.ajax({
url: host + '/weather/' + city + '/' + uf + '/now',
type: 'GET',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async: true
}).done(function (JSONReturn) {
//Actions with JSONReturn
});
But here in Brazil we have some cities with accents and cedilla like "Avaí" from "SP", "Mairiporã" from "SP" and "Missão Velha" from "CE".
If I send to the Endpoint an URL like "/weather/Americana/SP/now" or "/weather/Piracicaba/SP/now" the Endpoint gets the JSON return without problems.
But if I send to the Endpoint an URL like "/weather/Mairiporã/SP/now" or "/weather/Avaí/SP/now" the ClimaTempo API returns a null JSON and I get a NullPointerException.
I'm thinking that is a problem with the accents, but I can't send just "/weather/Mairipora/SP/now" without the accents because the ClimaTempo API demands that the city name must go with the accents, otherwise it returns a null JSON...
What am I doing wrong?
You need to encode and decode your characters.
Encode in JavaScript
Instead of url: host + '/weather/' + city + '/' + uf + '/now', go for
url: host + '/weather/' + encodeURIComponent(city) + '/' + uf + '/now'
Decode in Java
Instead of String newCityName = cityName.toLowerCase();, go for
String newCityName = URLDecoder.decode(cityName, Charsets.UTF_8.name()).toLowerCase();
Related
I have String Json:
String data = "param:"+"{\"dataFile\": \n" +
"{\"user\": \"asdasdasd\", \n" +
"\"pwd\":\"vasdadsda\", \"email\": \"vasdasdasd#gg.com\" \n" +
"}\n" +
"}";
Then try to send post to API with webview JSON like this:
myWebView.postUrl("url.com", data.getBytes());
from API the json process with "param" key then get the value, but the json get from API is null, any clue ?
I post my data like this. You may also try with this.
String postData = null;
try {
postData = "email=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.EMAIL), "UTF-8") + "&password=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.PASSWORD), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
webview.postUrl("url.com",postData.getBytes());
I'm building a web with spring that will allow the user to see the repositories, their issues and add new issues if they want. The problem appears when the user wants to create a new issue. I get "Error 400 Bad Request" and I can not underestand why.
I've tried to send the request through URL parameters but it didn't work either. I've also tried to automatically create the body with an ObjectMapper but I got the same result. So I'm building the body by myself but... same result again.
At the line with the comment "XXX" is where the software fails and in the web shows me the mentioned error.
#PostMapping("newIssue/{user}/{repo}/{fullName}")
public String registerUser(#PathVariable String user, #PathVariable String repo, #PathVariable String fullName, #Valid NewIssue newissue, Errors errors, Model model, OAuth2AuthenticationToken authentication) throws JsonProcessingException {
//To debug
System.out.println("### Registering issue");
//Check errors
List<String> errorsStrings = new ArrayList<>();
errors.getAllErrors().forEach(e->errorsStrings.add(e.getDefaultMessage()));
model.addAttribute("errors", errorsStrings);
model.addAttribute("newissue", newissue);
if(errors.hasErrors()) {
//To debug
System.out.println("### HAS ERRORS");
for (String err: errorsStrings )
System.out.println(" " + err);
//If has errors show again the page
return "newIssue";
}
//To debug
System.out.println("### Does not have ERRORS");
//Create the client variable
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient( authentication.getAuthorizedClientRegistrationId(), authentication.getName() );
//Construct the necessary headers
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "token " + client.getAccessToken().getTokenValue());
headers.add(HttpHeaders.ACCEPT, "application/vnd.github.v3+json");
//Construct the html petition's body
ObjectMapper mapper = new ObjectMapper();
//String body = mapper.writeValueAsString(newissue);
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": none,\n" +
" \"labels\": []\n" +
"}"
;
//Merge the header and the body
HttpEntity<String> request = new HttpEntity<String>(body, headers);
//To debug
System.out.println("### Going to send post: ");
System.out.println(body);
//Send the issue to the api
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("https://api.github.com/repos/" + user + "/" + repo + "/issues", HttpMethod.POST, request, String.class); //XXX
//To debug
System.out.println("### Post sent");
//To debug
System.out.println("### RESPONSE: " + response);
//Go to the repos' issues webpage
return "redirect:issues/"+user+"/"+repo+"/"+fullName;
}
I expected this method to create the new issue in the repository and then redirect to the repository's list of issues.
I've checked the body and it seems to be correct to me:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": none,
"labels": []
}
I did it all consulting the GitHub api documentation: https://developer.github.com/v3/issues/#create-an-issue
According to the documentation you provided under 'Create an issue', the value for "milestone" should be an Integer. Therefore, looking at your request, none is not an integer. I'm not sure what int you would supply in the request but I don't believe 'none' would work.
String body =
"{\n" +
" \"title\": \"" + newissue.getTitle() + "\",\n" +
" \"body\": \"" + newissue.getBody() + "\",\n" +
" \"assignees\": [],\n" +
" \"milestone\": 0,\n" +
" \"labels\": []\n" +
"}"
;
This would create the following body:
{
"title": "TestTitle",
"body": "TestBody",
"assignees": [],
"milestone": 0,
"labels": []
}
In addition, looking at the 'List issues for a repository' section, it appears they mention to only use "none" as a String.
As Brandon and NeplatnyUdaj said the issue was probably related with the "milestone line" because it was mandatory to be an integer. I put "none" because I did not want to add any milestone and it is the keyword used if you want to remove the milestones after the creation of the issue.
Thanks to the people that answered me I figured out that you could remove the "milestone line" due there is no way to telling the API that "there are no milestones" in the creation of the issue (despite you can remove all the milestones after the creation according to the documentation).
Than you all!
I'm trying to send an AJAX jQuery request to my Spring MVC Servlet and got some problems. I read some articles already but they didn't help me :(
So I have this ajax request:
$.ajax({
url : "add_news",
type : "POST",
dataType : 'json',
contentType : 'application/json',
mimeType : 'application/json',
data : JSON.stringify({"category": categoryName, "name": newsName, "data": newsData}),
success : function(data) {
$("#list_news").append(
data.id + " : " +
data.name + " - " +
data.created + " ; " +
data.data + "<br>");
}
});
Controller is:
#RequestMapping (value = "/add_news", method = RequestMethod.POST)
public #ResponseBody News addNews(#RequestParam String category, #RequestParam String name, #RequestParam String data) {
System.out.println("category " + category);
System.out.println("name " + name);
System.out.println("data " + data);
NewsCategoryDict c = new NewsCategoryDict();
c.setId(66);
c.setName("misc");
News response = new News();
response.setCategory(c);
response.setId(60);
response.setName(name);
response.setData(data);
response.setCreated(new java.util.Date());
return response;
}
I don't even get System out - so my first problem is with url. "add_news" is not a jsp - just a logic to get a record from server.
Second problem (if I undestand it right) in entry params. I have to use #RequestBody to get data from the client as Java POJO and send this POJO back with some additional info. But I don't understand how to write JSON body in AJAX.data right to make it valid.
Please help me.
EDIT
Ok. I find a moment. If I use GET in $.ajax AND set RequestMethod.GET in controller handler method - method is invoked (with POST - no actions). So why POST is not working ??
Remove JSON.stringify() from post data:
$.ajax({
url : "add_news",
type : "POST",
dataType : 'json',
contentType : 'application/json',
mimeType : 'application/json',
data : {"category": categoryName, "name": newsName, "data": newsData},
success : function(data) {
$("#list_news").append(
data.id + " : " +
data.name + " - " +
data.created + " ; " +
data.data + "<br>");
}
});
Please help me to send a JSON object in POST HTTP request through HttpClient, in Android.
The problem I am facing is that the JSON object having the URL is replaced by forward slash ,i.e
originally it should have the following value in JSON object
{"product":
{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg,
"short_description":"this is a test","title":"Raiders from the North"}
}
i tried many options to keep it in the above format. But it always comes as {"featured_src":
We assume this is your input
private final static String JSON_DATA = "{"
+ " \"product\": ["
+ " {"
+ " \"featured_src\": \"https:\\/\\/example.com\\/wp-content"
+ "\\/uploads\\/2015\\/06\\/sidney-compressed.jpg\","
+ " \"short_description\": \"this is a test\","
+ " \"title\" : \"Raiders from the North\""
+ " }"
+ " ]"
+ "}";
You could use replace to do the trick.
YOUR_STRING.replace("\\", "");
Finally your method would look like this, by passing your string as parameter
private static String jsonUrlCorrector(String json_data) {
json_data = json_data.replace("\\", "");
return json_data;
}
Here is the input:
{"product":[{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg","short_description": "this is a test","title":"Raiders from the North"}]}
Here is the output
{"product":[{"featured_src":"https://example.com/wp-content/uploads/2015/06/sidney-compressed.jpg","short_description":"this is a test","title":"Raiders from the North"}]}
EDIT 2
Found my error i was passing invalid an invalid parameter just remebered i was tryiong out stuff.
Sorry For the Trouble GUYS
I am using Google custom search engine for the first time and so far every thing is fine. However, when i try to send a query for an item which has a white space the search engine returns a bad request response eg
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ q.replace(" ", "%20") + "&searchType=" + searchType
+ "&imgType=" + imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
This returns this
com.google.api.client.http.HttpResponseException: 400 Bad Request
EDIT
i took the advice of 323go and tried encoding my q and this is how i implemented it
String encodedParms = null;
try {
encodedParms = URLEncoder.encode(q, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ encodedParms + "&searchType=" + searchType + "&imgType="
+ imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
Log.d(Tag, myUrl);
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request;
try {
request = httpRequestFactory.buildGetRequest(new GenericUrl(myUrl));
String response = streamToString(request.execute().getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In my log i got this as the url
https://www.googleapis.com/customsearch/v1?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-w&cx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Sunway+Lagoon+Theme+Park&searchType=image&imgType=photo&imgSize=xxlarge&num=20&alt=json
i still got the same bad request error
please can anyone tell me what i am doing worng
Why dont you add "+" between words, I had same issue
With "word1 word2" - response 400 - Bad request
With "word1+word2" - response 2000 - Bad request