簡體   English   中英

如何在JAX-RS中從@POST結束返回GET響應

[英]How to return GET response from @POST end in JAX-RS

我有這個,

@POST
@Path("/login")
public Response postLogin() throws IOException, SQLException,NamingException {
    return Response.temporaryRedirect(URI.create("localdir")).build();
}

它返回POST。 但是我想獲得同一篇文章的GET方法。

我怎樣才能做到這一點?

嘗試這個,

@POST
@Path("/login")
public Response postLogin() throws IOException, SQLException,NamingException {

    URL obj; 

    obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();         
    return response;
}

要么,

@POST
@Path("/login")
public Response postLogin() throws IOException, SQLException,NamingException {

    Request.Get("your url").execute().returnContent();
}

要么,

@POST
@Path("/login")
public Response postLogin() throws IOException, SQLException,NamingException {
    String uri = "your url";
    HttpParams httpParams = new BasicHttpParams();
    HttpClient client = new DefaultHttpClient(httpParams);
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);
    String responseStr = buildResponseFromEntity(response.getEntity());

    private String buildResponseFromEntity(HttpEntity entity)throws IllegalStateException, IOException {

        BufferedReader r = new BufferedReader(new InputStreamReader(entity.getContent()));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
        }
        return total.toString();
    }
    // check if error
    if (response.getStatusLine().getStatusCode() != 200) {
        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(responseStr);
        } catch (Exception e) {
            // do your code
        }
    }
}

盡管答案是正確的,並且由於我將其用於HTML,所以這是一種簡單的方法。

    String s = "<script>window.location.href="%s"</script>";
    s = String.format(s, "localdir");
    return Response.status(Response.Status.OK)
            .entity(s)
            .build();

暫無
暫無

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

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