Send an Array with an Http Get

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

Send array of objects via GET request with Angular's $http to Java Spring

You can transform your string and use a delimiter, then parse it on your server side. You can also use HttpPost instead of HttpGet request so you can send JSON String and it is easier to parse.

How to pass an array within a query string in HttpClient?

I think the best way is to add them to parameters as a string and have your back-end convert it back to an array or list.

let actorList = ['Elvis', 'Jane', 'Frances']
let params = new HttpParams();
params = params.append('actors', actorList.join(', '));
this.http.get(url, { params: params });

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}

How to encode an array as a http get parameter?

If you need a string like lang, created_at then simply place one there.

params = {
"max_results": 100,
"tweet.fields": "lang,created_at",
"query": "%23test"
}

You can also automatically generate one with .join method.

params = {
"max_results": 100,
"tweet.fields": ",".join(["lang", "created_at"]) ,
"query": "%23test"
}

Javascript - How to pass array elements in batches of 99 to HTTP POST request and continue HTTP POST's until all array elements have been passed

I was able to figure this out. Adding another "counter" mechanism batchCounter below, modifying the and if criteria to use this new batchCounterinstead of the same batchMaker, then resetting the value of this batchCounter variable so that for every subsequent loop/batch batchCounter and batchMaker interact the same as they did the very first loop (i.e. batchMaker == batchCounter +1 before meeting the 'if' statement criteria), and lastly breaking the loop entirely when recipientsProcessed begins to process 'undefined', that is a non-existence index number within my array which is displayed in the code as listComplete + 1 == recipientsProcessed. Here is the entire updated code snippet that is currently working as intended:

        var pageSelecterRadioButton = document.querySelector(
'input[name="page_selecter"]:checked'
);
var pageSelected = pageSelecterRadioButton.value;
var listComplete = allRecipients.length;
var batchCounter = 0;
var batchMaker = 0;
var batchRecipients;
var batchNumber = 0;
var recipientsProcessed = 0;
for (batchMaker = 0; batchMaker < 99; batchMaker++) {
batchRecipients =
allRecipients[recipientsProcessed] + `","` + batchRecipients;
console.log(
"Building Batch #" +
(batchNumber + 1) +
':"' +
batchRecipients.slice(0, -11)
);
batchCounter++;
recipientsProcessed++;
if (batchCounter == 99 || listComplete == recipientsProcessed) {
console.log(`"` + batchRecipients.slice(0, -11));
var subjectLineRaw = document.getElementById("subject").value;
var messageBodyRaw = document.getElementById("body").value;
const subjectLine = subjectLineRaw.replace(/(\r\n|\n|\r)/gm, " ");
const messageBody = messageBodyRaw.replace(/(\r\n|\n|\r)/gm, " ");
var data =
`{
"to": ["` +
batchRecipients.slice(0, -11) +
`],
"title": "` +
subjectLine +
`",
"body": "` +
messageBody +
`",
"sound": "default",
"data": {"event": "` +
pageSelected +
`"}
}`;
console.log(data);

var xhr = new XMLHttpRequest();
var url =
"https://stormy-peak-86652.herokuapp.com/https://exp.host/--/api/v2/push/send";
xhr.open("POST", url);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("content-type", "application/json");

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
console.log(data);
console.log(xhr);
xhr.send(data);
console.log(
"Push Notification POST batch #" + ++batchNumber + "complete!"
);
batchCounter = 2;
batchMaker = 0;
var batchRecipients = " ";
}
if (listComplete + 1 == recipientsProcessed) {
alert(recipientsProcessed - 1 + " Push Notifications Sent!");
break;
}
}
}

There were some other additions made in the snippet above as well, but nothing that really involves the question here (added task to handle radio button value, and inputting that additional content in the HTTP Post, etc.). Hope this helps someone else someday!

How to send a GET request with an array as a parameter?

import 'dart:async';
import 'package:wnetworking/wnetworking.dart';

class MangaDex {
static const _base = 'https://api.mangadex.org';

static FutureOr<void> _getter({required String url, required Function(JMap item, int idx) onItem}) async {
await HttpReqService.getJson<JMap>(url)
.then((response) {
var results = response?['results'];
if (results != null) {
if (results is List) {
var i = 0;
results.forEach((manga) => onItem(manga, ++i));
} else {
print(response);
}
}
});
}

static FutureOr<void> cover({int limit = 10, int offset=0, String? mangaId, String? coverId}) async {
final mangas = mangaId != null ? '&manga[]=$mangaId' : '';
final covers = coverId != null ? '&ids[]=$coverId' : '';
final url = '$_base/cover?limit=$limit&offset=$offset$mangas$covers';

await _getter(
url: url,
onItem: (item, idx) {
print('$idx) "${item['data']?['attributes']?['fileName']}"');
print(' id: ${item['data']?['id']}\n');
},
);
}
}

void main(List<String> args) async {
await MangaDex.cover(mangaId: '32d76d19-8a05-4db0-9fc2-e0b0648fe9d0', limit: 2);
print('\nJob done');
}

Result:

1) "f5873770-80a4-470e-a11c-63b709d87eb3.jpg"
id: b6c7ce9c-e671-4f26-90b0-e592188e9cd6

2) "e9f926db-b469-48c4-8cc4-a8e523ad75ca.jpg"
id: 00aae6e0-46bb-4f92-a82a-1c740789b704

Job done

Replace wnetworking package with http package, and JMap with Map<String, dynamic>

NOTE: MangaDex Documentation is lacking and misleading about how to correctly use its endpoints.



Related Topics



Leave a reply



Submit