简体   繁体   English

如何在JAX-RS中从@POST结束返回GET响应

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

I have this, 我有这个,

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

It returns POST. 它返回POST。 But I wanted to get GET method of same post. 但是我想获得同一篇文章的GET方法。

How can I do that? 我怎样才能做到这一点?

Try this, 尝试这个,

@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;
}

Or, 要么,

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

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

Or, 要么,

@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
        }
    }
}

Even though the answer is right, and since I am using it for HTML, here is an easy hack way to do it. 尽管答案是正确的,并且由于我将其用于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