I have an requirement to pass a some values from mobile to server in a web service call and so I am planning to pass all the values in JSON format like the below
<
You can pass your json Input as a POST request along with authorization header in this way
public static JSONObject getHttpConn(String json){
JSONObject jsonObject=null;
try {
HttpPost httpPost=new HttpPost("http://google.com/");
org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
StringEntity stringEntity=new StringEntity("d="+json);
httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
String authorization="test:test@123";
String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());
httpPost.addHeader("Authorization", security.get("Authorization"));
httpPost.setEntity(stringEntity);
HttpResponse reponse=client.execute(httpPost);
InputStream inputStream=reponse.getEntity().getContent();
String jsonResponse=IOUtils.toString(inputStream);
jsonObject=JSONObject.fromObject(jsonResponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
This Method will return a json response.In same way you can use GET method
As @RE350 suggested passing the JSON data in the body in the post would be ideal. However, you could still send the json object as a parameter in a GET request, decode the json string in the server-side logic and use it as an object.
For example, if you are on php you could do this (use the appropriate json decode in other languages):
Server request:
http://<php script>?param1={"nameservice":[{"id":89},{"id":3}]}
In the server:
$obj = json_decode($_GET['param1'], true);
$obj["nameservice"][0]["id"]
out put:
89
I encountered the same need and make a universal solution (node+browser) that works with the Next.js framework, for instance.
It even works with circular dependencies (thanks to json-stringify-safe
).
Although, I also built a serializer on top of it to remove unnecessary data (because it's not recommended to use a url longer than 2k chars, see What is the maximum length of a URL in different browsers?)
import StringifySafe from 'json-stringify-safe';
export const encodeQueryParameter = (data: object): string => {
return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};
export const decodeQueryParameter = (query: string): object => {
return JSON.parse(decodeURIComponent(query));
};
And the unit tests (jest):
import { decodeQueryParameter, encodeQueryParameter } from './url';
export const data = {
'organisation': {
'logo': {
'id': 'ck2xjm2oj9lr60b32c6l465vx',
'linkUrl': null,
'linkTarget': '_blank',
'classes': null,
'style': null,
'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
'mimeType': 'image/png',
'__typename': 'Asset',
},
'theme': {
'primaryColor': '#1134e6',
'primaryAltColor': '#203a51',
'secondaryColor': 'white',
'font': 'neuzeit-grotesk',
'__typename': 'Theme',
'primaryColorG1': '#ffffff',
},
},
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';
describe(`utils/url.ts`, () => {
describe(`encodeQueryParameter`, () => {
test(`should encode a JS object into a url-compatible string`, async () => {
expect(encodeQueryParameter(data)).toEqual(encodedData);
});
});
describe(`decodeQueryParameter`, () => {
test(`should decode a url-compatible string into a JS object`, async () => {
expect(decodeQueryParameter(encodedData)).toEqual(data);
});
});
describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
test(`should encode and decode multiple times without altering data`, async () => {
const _decodedData: object = decodeQueryParameter(encodedData);
expect(_decodedData).toEqual(data);
const _encodedData: string = encodeQueryParameter(_decodedData);
expect(_encodedData).toEqual(encodedData);
const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
expect(_decodedDataAgain).toEqual(data);
});
});
});
I know this could be a later post, but, for new visitors I will share my solution, as the OP was asking for a way to pass a JSON object via GET (not POST as suggested in other answers).
I have used this in some cases where I only can do GET calls and it works. Also, this solution is practically cross language.
I would suggest to pass the JSON data in the body as a POST
request.But if you still want to pass this as a parameter in URL,you will have to encode your URL like below just for example:-
for ex json is :->{"name":"ABC","id":"1"}
testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D
for more information on URL encoding refer below
https://en.wikipedia.org/wiki/Percent-encoding
I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand &
is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R
. So the acc parameter ends when it reaches the ampersand character.
That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.