我们如何通过java编码识别服务器响应代码。我的意思是,如果我们从服务器收到任何作为 HTTP 响应的响应,我们应该能够将其打印为字符串或其他任何内容。另外,我想知道我们如何在 java 中跟踪,如果某些特定请求被击到服务器并找出服务器响应代码。
问问题
2744 次
3 回答
2
在 Java 中,如果您想访问 http 标头代码,可以使用:
URL url = new URL("http://www.google.com");
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
openConnection.connect();
int rCode = openConnection.getResponseCode());
于 2012-04-05T10:58:29.977 回答
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;
}
于 2012-04-05T11:15:30.237 回答
0
您可以调用HttpResponse.getStatusLine().getStatusCode()来获取状态码:http ://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html
为了获取响应实体,您调用HttpResponse.getEntity()。
于 2012-04-05T12:47:21.957 回答