用java怎么获得get请求返回的结果中resultresult是list类型并转换为list类型使用
<p>可以使用Java的HttpURLConnection类发送GET请求,并读取返回的结果。然后使用JSON库将结果转换为List类型。</p>
<p>以下是一个示例代码:</p>
<pre><code class="language-java">import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.alibaba.fastjson.JSON;
public class Main {
public static void main(String[] args) {
try {
String url = "http://example.com/api/getData";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方式为GET
con.setRequestMethod("GET");
// 读取返回的结果
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 将结果转换为List类型
String result = response.toString();
List<Object> list = JSON.parseArray(result, Object.class);
// 处理List数据
for (Object obj : list) {
// TODO: 处理每个对象
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>在上面的示例代码中,我们使用了阿里巴巴的fastjson库将返回的结果转换为List<Object>类型。如果你使用的是其他JSON库,可以根据其API进行转换。</p>
原文地址: https://www.cveoy.top/t/topic/4Vc 著作权归作者所有。请勿转载和采集!