2016-08-19 148 views
0

我有以下类从json响应中返回一个spefic字段。 这里要求的方法是在帖子后面。我如何使用get方法做​​到这一点? 此外,我想用头用Json响应获取请求?

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)GET请求;

回答

1

尝试......

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块全封闭式。