如何使用java查找服务器响应代码

如何使用java查找服务器响应代码,java,jakarta-ee,Java,Jakarta Ee,如何通过java编码识别服务器响应代码。我的意思是,若我们从服务器得到任何作为HTTP响应的响应,我们应该能够将其打印为字符串或其他形式。另外,我想知道如果某个特定的请求被发送到服务器,我们如何在java中跟踪,并找出服务器响应代码 在Java中,如果您想访问http头代码,可以使用: URL url = new URL("http://www.google.com"); HttpURLConnection openConnection = (HttpURLConnection) url.ope

如何通过java编码识别服务器响应代码。我的意思是,若我们从服务器得到任何作为HTTP响应的响应,我们应该能够将其打印为字符串或其他形式。另外,我想知道如果某个特定的请求被发送到服务器,我们如何在java中跟踪,并找出服务器响应代码

在Java中,如果您想访问http头代码,可以使用:

URL url = new URL("http://www.google.com");
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
openConnection.connect();
int rCode = openConnection.getResponseCode());

如果您使用URLConnection,那么此代码将帮助您,并且您可以将HTTP响应打印为字符串

String output = null;
output = getHttpResponseRabby("input url link");

public static String getHttpResponseRabby(String location) {

    String result = "";
    URL url = null;
    Log.d("http:", "balance information");

    try {
        url = new URL(location);
        Log.d("http:", "URL Link" + url);
    } catch (MalformedURLException e) {
        Log.e("http:", "URL Not found" + e.getMessage());
    }

    if (url != null) {
        try {
            BufferedReader in;
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(1000);
            while(true)
            {
                try 
                    {
                     in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    } 
                catch (IOException e) 
                    {
                        break;
                    }


                String inputLine;

                int lineCount = 0; // limit the lines for the example
                while ((lineCount < 5) && ((inputLine = in.readLine()) != null)) 
                    {
                        lineCount++;

                        result += inputLine;
                    }

                in.close();
                urlConn.disconnect();
                return result;
           }
        } catch (IOException e) {
            Log.e("http:", "Retrive data" + e.getMessage());
        }
    } else {
        Log.e("http:", "FAILED TO RETRIVE DATA" + " url NULL");
    }
    return result;
}
您可以调用以获取状态代码:


以及获取您调用的响应实体。

您是否希望更具体一些,比如您使用的是HttpClient或URLConnection,还是您自己的实现?抱歉,我使用HttpClient进行请求,然后您可以调用HttpResponse.getStatusLine.getStatusCode获取状态代码:请编辑您的问题@aditi并提供有关HttpClient的更多详细信息。显示一些代码。我知道你现在有你的答案,但这是给其他有同样问题的人的。@ahanin请将你的评论作为答案,以便接受。