Having some issue encoding in Java

186 katselukertaa
Siirry ensimmäiseen lukemattomaan viestiin

Mohamed Faliq

lukematon,
19.8.2021 klo 11.28.3019.8.2021
vastaanottaja astrometry

So Im trying to translate a working python code into Java. One of the steps required is to url encode the data. But when I encode the data in Java it looks different than the one in encoded in Python.

In one of the block of Python code theres this:

data = {'request-json': json} 
print('Sending form data:', data) 
data = urlencode(data) 
data = data.encode('utf-8') 
print('Sending data:', data)

The Output

Sending form data: {'request-json': '{"apikey": "xewpjipcpovwiiql"}'}

The output after being encoded

Sending data: b'request-json=%7B%22apikey%22%3A+%22xewpjipcpovwiiql%22%7D'

So this is what im trying to do in Java. As you can imagine Java is more involved. I used gson to convert to Json

Gson gson = new Gson(); 
API_Key key = new API_Key("xewpjipcpovwiiql"); 
String jsonInputString = gson.toJson(key); 
Data data = new Data(key); 
String request_form = gson.toJson(data); 
System.out.println(request_form);
String urlencoded = URLEncoder.encode(request_form,StandardCharsets.UTF_8); System.out.println(urlencoded);

The output:

Sending form data: {"request-json":{"apikey":"xewpjipcpovwiiql"}}

The output of the encoded string:

%7B%22requestjson%22%3A%7B%22apikey%22%3A%22xewpjipcpovwiiql%22%7D%7D

So they dont look the same so why are they coming differently ? How do I get the same python encoded String in Java ? 

I noticed in Python it used a combination of single and double quotes and in Java its only Double quotes so I dont know if that makes a difference. And Does spaces between the brackets matter ?

Thank You!

Reply all
Reply to author
Forward

Dustin Lang

lukematon,
19.8.2021 klo 12.13.1119.8.2021
vastaanottaja Mohamed Faliq, astrometry
Hi,

I think this part is wrong:
String request_form = gson.toJson(data);

you should not be forming a second JSON string; you want to be formatting an x-www-form-urlencoded URL encoding of the key-value pair "request-json" and the JSON-encoded API key dictionary.  Java's URLEncoder doesn't do that; it only takes a String, so you either need to find a function that will make that URL encoding for you, or do it yourself; I tihnk it's just "request-json=" + jsonInputString.

cheers,
--dustin



--
You received this message because you are subscribed to the Google Groups "astrometry" group.
To unsubscribe from this group and stop receiving emails from it, send an email to astrometry+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/astrometry/dd22a995-940c-475a-936d-a5c6d28a02d6n%40googlegroups.com.
Vastaa kaikille
Vastaa kirjoittajalle
Välitä
0 uutta viestiä