gpt4 book ai didi

java - 获取带有 Json 响应的请求?

转载 作者:行者123 更新时间:2023-12-01 09:35:10 31 4
gpt4 key购买 nike

我有以下类,它从 json 响应返回特定字段。这里请求的方法是用post。我怎样才能用get方法做​​到这一点?我还想发出带有 header 的 get 请求

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(
"");
post.addHeader("Auth-Token", authenticationValues.getAuthToken());
post.addHeader("device-id", authenticationValues.getDeviceId());

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
String generatedJSONString = null;
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;

try {
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());

while (in.hasNext()) {
JsonString += in.next();

}

EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(JsonString);

JSONObject jsonObject = new JSONObject(JsonString);
JSONObject myResponse = jsonObject.getJSONObject("login");
Object myResponse2 = myResponse.get("loginStatus");

System.out.println(myResponse2);

最佳答案

试试这个...

URL url = new URL("http://"...);
HttpURLConnection http = (HttpURLConnection)
url.openConnection();
http.setRequestMethod("GET");
http.setDoOutput(true);
http.connect();

OutputStream out = http.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(FOO);
writer.flush();
writer.close();

InputStreamReader in = new InputStreamReader(http.getInputStream());
BufferedReader br = new BufferedReader(in);

char[] chars = new char[BUF_SIZE];
int size = br.read(chars);

String response = new String(chars).substring(0, size);

全部包含在 try-catch block 中。

关于java - 获取带有 Json 响应的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39040782/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com