簡體   English   中英

如何從響應中獲取數據

[英]How to get data from response

我創建了2個Web服務,我能夠發送一些數據。

使用這三行代碼

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);

在這種情況下,我發布的方法向Web服務器發送了2個數據。

@Path("/domethod")
    // Produces JSON as response
    @Produces(MediaType.APPLICATION_JSON) 
    // Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
    public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
        String response = "";
        System.out.println("Data: d1="+d1+"; d2="+d2);
        if(checkData(d1, d1)){
            response = Utitlity.constructJSON("tag",true);
        }else{
            response = Utitlity.constructJSON("tag", false, "Error");
        }
    return response;        
    }

System.out工作正確並打印:d1 = abc; d2 = xyz但是現在應用程序無法返回對第一種方法的響應。 我如何得到答復?

你已經在這里得到了回復:

HttpResponse response = client.execute(request);

既然你已經在使用org.apache.httpcomponents你可以這樣做:

String result = EntityUtils.toString(response.getEntity());

之后,您將數據作為字符串,只需按照您的意願執行即可。

編輯:更多信息,您的數據在響應的實體中,這是一個HttpEntity對象。 你可以從那里獲取內容作為InputStream並按你的意願閱讀它,我的例子是一個簡單的字符串。

首先,我會用get方法進行注釋。 然后我會使用Java類,讓庫將類轉換為json。

嘗試這樣做:

@GET
@Path("/domethod")
    // Produces JSON as response
    @Produces(MediaType.APPLICATION_JSON) 
    // Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
    public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
        Response response = new Response();
        System.out.println("Data: d1="+d1+"; d2="+d2);
        if(checkData(d1, d1)){
            //set in response the tag property to true and maybe another property to OK
            response.setTag(true);
            response.setStatus("OK");
        }else{
             //set in response the tag property to false and maybe another property to ERROR
            response.setTag(false);
            response.setStatus("ERROR");
        }
    return response;        
    }

暫無
暫無

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

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