构造普通http请求
对于不需要用户名与密码认证的连接,一般只需要构造好URIBuilder随后发起get请求即可获得返回信息,具体代码如下
CloseableHttpClient client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder("http://" + ip_addr + ":" + port);
HttpGet httpGet = new HttpGet(uriBuilder.build());
CloseableHttpResponse response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
response.close();
client.close();
}
构造带有认证的Http请求
当请求需要用户名与密码的认证时,需要构造一个httpclient包下的UsernamePasswordCredentials对象,通过这样一个验证对象来提醒这是一个带有验证的请求。在实际操作的过程中,往往需要一并设置请求头user-agent,不然也可能会返回401状态码,以下是代码示例。
HttpClient httpClient = new HttpClient();
org.apache.commons.httpclient.UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.username, this.password);
httpClient.getState().setCredentials(AuthScope.ANY, creds);
List<Header> headers = new ArrayList<Header>();headers.add(new Header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));
httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
GetMethod method = new GetMethod("http://" + ip_addr + ":" + port);
method.setDoAuthentication(true);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("Method failed code=" + statusCode + ": " + method.getStatusLine());
} else {
InputStream inputStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String s;
StringBuffer sb = new StringBuffer();
while ((s = br.readLine()) != null) {
sb.append(s + "\n");
}
result = sb.toString();
System.out.println(new String(method.getResponseBody(), "utf-8"));
}
} finally {
method.releaseConnection();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)