簡體   English   中英

獲得有關Json響應的請求?

[英]Get request with Json response?

我有以下從json響應返回特殊字段的類。 在此請求的方法是post。 我該如何使用get方法呢? 我也想用標頭發出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塊中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM