I want to post array param in HttpURLConnection android - java

I am a fresher in developing Android apps, in my app I want to post params in the format below:
user_id=12&task_id=100&user_ids=["91","92"]
I am not able to send the user_ids in array format. I am receiving the user_ids as string in my Rails API.
I am using HttpURLConnection, and in my writer.write() I am passing my post params as
writer.write("user_id="+id+"&task_id="+tid+"&user_ids="+["91","92"]+");
Please help.

If any one facing the same problem, I found a work around.
You need to add the array in a string
1. Step 1
Create a final ArrayList<String> SelectedTagIds = new ArrayList<String>();
and add the array items using
SelectedTagIds.add("One");
SelectedTagIds.add("Two");
...
2. Step 2
Convert
SelectedTagIds.toString();
3. Step 3
Format the String by replacing the string to
SelectedTagIds.replace("[","").replace("]","").replaceAll("\\s","").trim();
4 Step 4
Finally post the String to the server (I used HttpURLConnection to post my data to the server), and in the server code, convert the received SelectedTagIds to Array and loop accordingly to achieve you'r desired result.

Related

How to retrieve AWS Textract response JSON using the Java SDK

I am using AWS Textract to OCR images and create a searchable PDF as outlined in this AWS blog post.
The basic request code looks like this:
AmazonTextractClientBuilder builder = AmazonTextractClientBuilder.standard();
DetectDocumentTextRequest request = new DetectDocumentTextRequest()
.withDocument(new Document()
.withBytes(imageBytes));
DetectDocumentTextResult result = client.detectDocumentText(request);
List<Block> blocks = result.getBlocks()
This works out great however I would also like to write out and keep the original response JSON that contains all the information on what was detected where etc.
Is there a way to get to the response JSON using the JAVA SDK?
AWS doesn't return the response JSON to you in raw form. The assumption may have been that it wouldn't be required once it has been converted to a DetectDocumentTextResult object.
You are able to convert the DetectDocumentTextResult object to JSON (example) which should provide identical values. Note that the variable names will not be identical (e.g.: DocumentMetadata vs documentMetadata) but the values of those variables will be the same.

Send String to server without back slash

I am sending data (using Retrofit) to server like below way
"[\"emailaddress\"]"
But server need that data in below way
["emailaddress"]
I have tested in PostMan, only ["emailaddress"] works fine..
I have tried below code which is not giving me result what server wants.
var emailArray = "[\"$email\"]"
Can anyone help me how can i achieve that?
What should I need to change to make it as server wants?
Can you create json array object and put the content in it .. like below.
in Java this how you can acheive.
JSONArray postdata = new JSONArray();
postdata.put(<email address>);
and pass this to server by
postdata.toString();
So basically create array and push email to it, then while passing the data covert to string, that should work.
Escape the backslash in the regex.
Try this :
var emailArray = "[\"emailaddress\"]"
var emailArrayNew = emailArray.toString().replace("\\\\", "")
Could you try using List/ArrayList there?
val emailList = ArrayList<String>()
emailList.add("email1")
emailList.add("email2")
Then in Retrofit Api Service, do something like this
#Field("email") emailList:List<String>
Hope this will help you

How to use json array in order to use each item in the array to use values in a get request ?

I have a json array data file (pre-prepared) each item in the json array contain data which I want to be able to use in order to send a request to a server using the json array data file , i know how to be able to send one request after extracting data from the file but I am struggling of getting all the data to send one after another.
I want to imitate the following behavior which I wrote already in java:
List<Integer> mtl = Arrays.asList(new Integer[]{1, 9, 257, 265});
for(int i=0;i<jsonArray.size();i++){
JSONObject item = (JSONObject)jsonArray.get(i);
int dataFlagType = Integer.parseInt(item.get("DataFlagType").toString());
if(!(mtl.contains(dataFlagType))){
sendPushStream(Long.parseLong(m_ap.sid),pid,subsId,item,domain,dnsName,dataFlagType);
}else{
lastMessage = (JSONObject)jsonArray.get(i);
}
Thread.sleep(100);
}
Thread.sleep(100);
sendPushStream(Long.parseLong(m_ap.sid),pid,subsId,lastMessage,domain,dnsName,Integer.parseInt(lastMessage.get("DataFlagType").toString()));
where sendPushStream execute the post request itself.
I would suggest organizing your Test Plan as follows:
HTTP Request (Protocol: file, Path: /path/to/your/file.json
JSON Extractor (relevant JSONPath query to extract values and store them into JMeter Variables)
ForEach Controller to iterate the Variables coming from the JSON Extractor
HTTP Request - to mimic sendPushStream
Another option is using your Java code from JSR223 Sampler or JUnit Request sampler, just make sure you package your helper code as .jar and add it to JMeter Classpath

Returning multiple sets of data using JSON with Java and JQuery

I want to send sets of data from servlet to the jsp using JSON. To elaborate, what exactly I want to do is take multiple rows from the database and print their values in jsp. I done with the part of DB connectivity and fetching of data. But I could not find a way to forward them to jsp using JSONObject. Each row has multiple attributes(column values). Please help me solve the problem.
What I'm doing is:
Collection <JsonObject> c=new ArrayList();
JsonObject j[] = null;
for(int i=0;i<uid_list.size();i++){//uid_list contains all the user_id's from the database
j[i].add("uid", j[i]);
j[i].add("fname", j[i]);
j[i].add("lname", j[i]);
j[i].addProperty("uid", uid_list.get(i).toString());
j[i].addProperty("fname", fname_list.get(i).toString());
j[i].addProperty("lname", lname_list.get(i).toString());
c.add(j[i]);
}
Also, is there any difference between JsonObject and JSONObject? The latter could not be recognized in servlet and by using JsonObject the put method is not recognized.
Aside from your code trying to insert into an uninitialized array, there are many JSON library for Java. You need to provide more details which one you're using
Also if your objective is just passing the JSON string into the browser, you might not even need jsp, you can just write the string version of the JSON object directly into the HttpResponse
Firstly, the JspnObject array has to be instantiated before it is used. Therefore, this means the following:
JsonObject j[] = new JsonObject[noOfObjects to be iterated]

Doing HTTP post of JSON object every second

I have to do a HTTP post in java every second after building a json object.
The json object is built from reading a CSV file which is huge (200Mbs+), so my problem is
how do I read x number of lines build x objects and post that every second(as it is not possible to parse the whole 200mb file in less than a second) and continue reading the next x lines.
Please let me know your thoughts..
Can I use Java timer class, and keep reading the CSV file and at the same time post the json object to the server every second with the formed json?
It is hardly possible to read, parse, convert and send a 200 MB file once per second.
So you need to change your design:
My suggestion would be to only send changed lines, something like this:
{
"1" : {"field1":"value1","field2":"value2"},
"17" : {"field1":"value1","field2":"value2"}
}
Which of course gives you new problems:
The client needs to figure out which lines have changed, and the server needs to integrate the changed lines with the existing data.
I would make it depending on the file size and not depending on time.
BufferedReader fin = null; //create it
Gson gson=new Gson(); //Google code open source library for JSON in Java
ArrayList<JSONObject> jsonList=new ArrayList<JSONObject>();
while (((line = fin.readLine()) != null)) {
if ( line.length()==0 ){
//"Blank line;
}else{
currJSON=loadJSON(line);//You have to load it in a Java Object
if ( jsonList.size()<MAX_JSON){
jsonList.add(currJSON);
}
if (JsonList.size()==MAX_JSON){ //Define the maximum size of the list you want to post
gson.toJson(jsonList); //Convert to JSON
//You should post your Json with some Http Connection to your server
jsonList.clear();

Categories