How to Pass a JSON Array as a Parameter in Url

How to pass a JSON array as a parameter in URL

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

How to pass My JSON array as a parameter in URL

You can use my class:

public class HttpHelperConnection {

static String response = "";

//metodo pubblico per ottenere la risposta dal server settando tutti i parametri necessari

/**
*
* @param url
* @param method
* @param post_params
* @param connection_timeout
* @param reading_timeout
* @return
*/
public static String getSyncResponse(String url, String method, HashMap<String, String> post_params,
long connection_timeout, long reading_timeout){

response = "";
response = StartConnection(url, method, post_params, connection_timeout, reading_timeout);
return response;
}

public static String getAsyncResponse(String url, String method, HashMap<String, String> post_params,
long connection_timeout, long reading_timeout){

new Thread(() -> {
response = "";
response = StartConnection(url, method, post_params, connection_timeout, reading_timeout);
}).start();
return response;
}

private static String StartConnection(String url, String method, HashMap<String, String> post_params,
long connection_timeout, long reading_timeout){

String localResponse = "";

try{
URL url_encoded = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url_encoded.openConnection();
conn.setReadTimeout((int)reading_timeout);
conn.setConnectTimeout((int)connection_timeout);
conn.setRequestMethod(method);//il metodo si occupa da solo di inviare la stringa nel metodo richiesto
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("User-Agent", "Chrome");
conn.setRequestProperty("Accept-Encoding", "identity");

try (OutputStream out_stream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_stream, "UTF-8"))) {
writer.write(ricevoServerLoginResponse(post_params));
writer.flush();
}catch(IOException e){
System.out.print(e.toString());
}

if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {

}else {
localResponse=null;
System.out.println("Error to connect: " + Integer.toString(conn.getResponseCode()));
}
HttpHelperConnection class_conn = new HttpHelperConnection();
String return_code = class_conn.decodeUrlCode(conn.getResponseCode());
if(return_code.equals("OK")){
String line;
InputStreamReader stream_reader = new InputStreamReader(conn.getInputStream());
if (!url_encoded.getHost().equals(conn.getURL().getHost()))
System.out.println("redirectered");//nel caso il browser richiede un'autenticazione
BufferedReader br=new BufferedReader(stream_reader);
while ((line=br.readLine()) != null) {
localResponse+=line;
}
}else
localResponse = "error: " + return_code;
}catch(IOException e){
System.out.print(e.toString());
}
return localResponse;
}

//metodo privato per creare la stringa per i dati passati in post
private static String ricevoServerLoginResponse(HashMap<String, String> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){//passo ogni dato interno all'hash map
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}

return result.toString();
}

private String decodeUrlCode(int res_code){
switch(res_code){
case HttpsURLConnection.HTTP_OK :
return "OK";
case HttpsURLConnection.HTTP_ACCEPTED :
return "HTTP_ACCEPTED";
case HttpsURLConnection.HTTP_BAD_GATEWAY :
return "HTTP_BAD_GATEWAY";
case HttpsURLConnection.HTTP_BAD_METHOD :
return "HTTP_BAD_METHOD";
case HttpsURLConnection.HTTP_BAD_REQUEST :
return "HTTP_BAD_REQUEST";
case HttpsURLConnection.HTTP_CLIENT_TIMEOUT :
return "HTTP_CLIENT_TIMEOUT";
case HttpsURLConnection.HTTP_CONFLICT :
return "HTTP_CONFLICT";
case HttpsURLConnection.HTTP_CREATED :
return "HTTP_CREATED";
case HttpsURLConnection.HTTP_ENTITY_TOO_LARGE :
return "HTTP_ENTITY_TOO_LARGE";
case HttpsURLConnection.HTTP_FORBIDDEN :
return "HTTP_FORBIDDEN";
case HttpsURLConnection.HTTP_GATEWAY_TIMEOUT :
return "HTTP_GATEWAY_TIMEOUT";
case HttpsURLConnection.HTTP_GONE :
return "HTTP_GONE";
case HttpsURLConnection.HTTP_INTERNAL_ERROR :
return "HTTP_INTERNAL_ERROR";
case HttpsURLConnection.HTTP_LENGTH_REQUIRED :
return "HTTP_LENGTH_REQUIRED";
case HttpsURLConnection.HTTP_MOVED_PERM :
return "HTTP_MOVED_PERM";
case HttpsURLConnection.HTTP_MOVED_TEMP :
return "HTTP_MOVED_TEMP";
case HttpsURLConnection.HTTP_MULT_CHOICE :
return "HTTP_MULT_CHOICE";
case HttpsURLConnection.HTTP_NOT_ACCEPTABLE :
return "HTTP_NOT_ACCEPTABLE";
case HttpsURLConnection.HTTP_NOT_AUTHORITATIVE :
return "HTTP_NOT_AUTHORITATIVE";
case HttpsURLConnection.HTTP_NOT_FOUND :
return "HTTP_NOT_FOUND";
case HttpsURLConnection.HTTP_NOT_IMPLEMENTED :
return "HTTP_NOT_IMPLEMENTED";
case HttpsURLConnection.HTTP_NOT_MODIFIED :
return "HTTP_NOT_MODIFIED";
case HttpsURLConnection.HTTP_NO_CONTENT :
return "HTTP_NO_CONTENT";
case HttpsURLConnection.HTTP_PARTIAL :
return "HTTP_PARTIAL";
case HttpsURLConnection.HTTP_PAYMENT_REQUIRED :
return "HTTP_PAYMENT_REQUIRED";
case HttpsURLConnection.HTTP_PRECON_FAILED :
return "HTTP_PRECON_FAILED";
case HttpsURLConnection.HTTP_PROXY_AUTH :
System.out.println("HTTP_PROXY_AUTH");
return "HTTP_PROXY_AUTH";
case HttpsURLConnection.HTTP_REQ_TOO_LONG :
return "HTTP_REQ_TOO_LONG";
case HttpsURLConnection.HTTP_RESET :
return "HTTP_RESET";
case HttpsURLConnection.HTTP_SEE_OTHER :
return "HTTP_SEE_OTHER";
case HttpsURLConnection.HTTP_UNAUTHORIZED:
return "HTTP_UNAUTHORIZED";
case HttpsURLConnection.HTTP_UNAVAILABLE :
return "HTTP_UNAVAILABLE";
case HttpsURLConnection.HTTP_UNSUPPORTED_TYPE :
return "HTTP_UNSUPPORTED_TYPE";
case HttpsURLConnection.HTTP_USE_PROXY :
return "HTTP_USE_PROXY";
case HttpsURLConnection.HTTP_VERSION :
return "HTTP_VERSION";
default :
return "UNKNOWN_ERROR";
}
}
}

You can run this from your Activity:

JSONObject jsobj;
String jsonString = jsonobj.toStirng();

HashMap<String, String> postParams = new HashMap<>();

postParams.put("datas", jsonString);

int connectionTimeout = 1000;
int readingTimeout = 1000;

//If you want connection in your thread
String resposne = HttpHelperConnection.getSyncResponse("https://yourUrl", "POST" , postParams, 1000 , 1000);

//If you want the connection in another thread
response = HttpHelperConnection.getAsyncResponse("https://yourUrl", "POST" , postParams, 1000 , 1000);

How to send Json array as post params in android open URL connection

This sample for your reference

String request = "your Url Here";

URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer Key");
conn.setRequestProperty("Content-Type", "application/json");

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

JSONArray jsonArray=new JSONArray();
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
jsonArray.put(jsonParam);

wr.writeBytes(jsonArray.toString());

wr.flush();
wr.close();

For more detail checkout here, here or here

Django - Passing a json or an array in URL for an API call

I am using axios to make calls from django backend. In my case I can do:

js.file:

function search(token, status, q) {
return (dispatch) => {
dispatch(start(token));
axios
.get(`${serverIP}/invoices/sales-invoice/`, {
params: {
status: status,
q: q,
},
})
.then((res) => {
dispatch(successSearch(res.data, status));
})
.catch((err) => {
dispatch(fail(err));
});
};
}

Here I am sending 2 params, but you can actually send object, for example user info.
And than in views get them

views.py:

def list(self, request, *args, **kwargs):
status = request.query_params.get('status')
q= request.query_params.get('q')

These is exapmple with DRF model viewset

How to pass content of json file as url param

In order to use template strings in javascript, you need to use the ` quotes, not the ' quotes.

// Write this:
const url = `https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit`;

// Not this:
const url = 'https://api.example-test.com/user-api/accounts/${randomUser.accountreference}/benefit';

How to Pass a JSON object as a parameter with an url?

Just pass it as a string, after encoding it:

var uri = "http://173.229.213.72:9000/index.html#/myurl?jsonObj={'property1':'val1', 'property2':54}";
var encodedUri = encodeURI(uri)
window.open(encodedUri );


Related Topics



Leave a reply



Submit