我们如何通过java编码识别服务器响应代码。我的意思是如果我们从服务器获得任何响应作为HTTP响应,我们应该能够将其打印为字符串或其他任何内容。另外,我想知道我们如何在java中跟踪,如果某个特定请求被命中到服务器并找到服务器响应代码。
答案 0 :(得分:2)
在Java中,如果您想要访问http标头代码,可以使用:
URL url = new URL("http://www.google.com");
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
openConnection.connect();
int rCode = openConnection.getResponseCode());
答案 1 :(得分:0)
如果您使用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;
}
答案 2 :(得分:0)