使用httpclient进行远程调用,需要的maven pom:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
代码如下:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* 通过httpclient进行访问
*
*/
public class HttpUtils {
/**
* 访问url方法
*
* @param url
* @return 请求结果,与ResponseHandler<String>指定的类型一致。
*/
public static String callOnHttp(String url) {
String address = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response)
throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity)
: null;
} else {
throw new ClientProtocolException(
"Unexpected response status: " + status);
}
}
};
message = httpclient.execute(httpget, responseHandler);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return message;
}
}
注:上面代码是Get方法,POST,DELETE,PUT方法及一些细节就不一一列出啦,apache为这些实现都封装好啦,需要的时候直接看API用就行啦!另外访问出错的时候,注意是否是自己请求不合被请求环境,比如请求头缺少啥信息,接口参数啥的。
比如我用HttpClient去连接读取一个网站时,老是会发生这个403错误。 google后知道了答案。原来如果用java代码HttpClient去连的话 http header 中的User-Agent就为空,解决方法就是在连接之前先设置这个属性。
HttpGet httpget = new HttpGet(url);
httpget.setHeader(“User-agent”,”Mozilla/4.0”);
那台Server上要这么做, 可能是要阻止一些网络机器人的访问(不过感觉不是很有用,用上面的方法就能破了)。 其实实现感觉也很简单, 加上一个Filter,判断如果request.getHeader(“User-agent”)为空的话,然后再response一个403 status就行。