简体   繁体   中英

How do I put data I have received from a Http request into an array?

I need to insert post request data into array. I will get three sets of JSON information and I want to insert each JSON result in a String array. Here is the code I am currently using.

URL url = new URL("http://localhost:9090/service.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer response = new StringBuffer();
int i = 0;
ArrayList<String> arr = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
        response.append(line);
        arr.add(response.toString());
        System.out.println(arr.get(i));
        i++;
    }

If input like:

abc
def
ghi

This code outputs like:

abc
abcdef
abcdefghi

But I need output like input.

Move

StringBuffer response = new StringBuffer();

to the first line in your 'while' block

You have not reinitialized your StringBuffer variable response. In addition, you don't really need to use StringBuffer , since you are not manipulating the string information. I suggest you try the following (and at some point you won't want to use localhost):

URL url = new URL("http://localhost:9090/service.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int i = 0;
ArrayList<String> arr = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
   arr.add(line);
   // debug information
   System.out.println(arr.get(i));
   i++;
}

change arr.add(response.toString()); to arr.add(line); and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM