您的位置:首页 > 理论基础 > 计算机网络

HTTP详解(四):JAVA实现HTTP请求

2017-08-06 08:55 78 查看

HTTP详解(四):JAVA实现HTTP请求

JAVA实现HTTP请求



通过上几篇的文章,我们对HTTP已经已经有了一个初步的认识,对于"为什么要用HTTP","怎么用HTTP","HTTP是什么"相信大家都有了一个了一个属于自己的看法,今天这篇文章主要是代码的角度上去实现HTTP的请求。
我们都知道,HTTP请求方法用的最多的就是POST和GET请求。我们今天就主要实现这两种方法的请求。
目前阶段,JAVA实现HTTP请求的方法用的最多的有两种:
一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求。
另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。
那我们开始吧!

GET请求的实现:
HttpURLConnection实现:
public static String doGet(String urlStr){
//用来存储返回报文
String resultStr = "";
//用于读取返回报文所创建的流
BufferedReader br = null;
try{
//第一步:获取URL,通过URL打开连接
URL url = new URL(urlStr);
//第二步:通过URL,打开连接,获取HttpURLConnection,url.openConnection()获取的是URLConnection,而HttpURLConnection继承URLConnection,所以需要强转
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
//第三步:设置一些通用属性
//设置请求方法
httpURLConnection.setRequestMethod("GET");
//设置连接超时时间
httpURLConnection.setConnectTimeout(10000);
//设置连接之后响应的超时时间
httpURLConnection.setReadTimeout(20000);
//让客户端与服务端保持连接
httpURLConnection.setRequestProperty("connection","Keep-Alive");
//第四步:建立实际的连接
httpURLConnection.connect();
//第五步:获取响应报文
if(200 == httpURLConnection.getResponseCode()){//200 代表着请求成功
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line;
while((line = br.readLine()) != null){
resultStr += line;
}
}
return resultStr;
}catch(Exception e){
logger.info("http get request exception error",e);
//将异常抛出的目的是:因为这种GET请求一般实在业务逻辑中使用,如果出现HTTP通信异常,将异常抛出,便于使用该方法的地方将异常捕获进行处理。
throw new RuntimeException("HTTP通信异常!");
}finally{
try {
if(br != null)
br.close();
} catch (IOException e) {
throw new RuntimeException("HTTP关闭IO出现异常!");
}
}
}
HttpClient实现:
public static String doGetByHttpClient(String url){
String result = "";
HttpClient client = null;
HttpMethod httpMethod = null;
try {
//第一步:获取HttpClient
client = new HttpClient();
//第二步:获取HttpMethod,并且设定请求方法为Get请求
httpMethod = new GetMethod(url);
//第三步:设置相应的一些属性
//设置请求头
httpMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
//设置连接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
//设置30秒内没有收到数据的话,则强制断开客户端
client.getHttpConnectionManager().getParams().setSoTimeout(30000);
//第五步:执行GET请求
client.executeMethod(httpMethod);
//第六步:获取返回报文,通过IO流进行读取
InputStream responseBody = httpMethod.getResponseBodyAsStream();
InputStreamReader in = new InputStreamReader(responseBody, "utf-8");
BufferedReader br = new BufferedReader(in);
StringBuffer stringBuffer = new StringBuffer();
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
stringBuffer.append(inputLine);
}
in.close();
result = stringBuffer.toString().trim();
} catch (Exception e) {
logger.error("HttpsUtil.doGet|http get request exception error ", e);
throw new RuntimeException("HTTP通信异常");
} finally {
if (httpMethod != null) {
httpMethod.releaseConnection();
}
}
return result;
}
上面就是两种不同的GET请求的实现方式。我们来总结一下。
(1)通过HttpURLConnection实现HTTP的GET请求的的步骤:
第一步:根据url获取URL对象:
URL url = new URL(urlStr);
第二步:使用URL获取HttpURLConnection:
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
第三步:建立连接:
httpURLConnection.connect();
第四步:获取响应报文,使用IO流读取响应报文
(2)通过HttpClient实现HTTP的GET请求
第一步:获取HttpClient
HttpClient client = new HttpClient
第二步:使用HttpMethod来确定请求方式
HttpMethod httpMethod = new GetMethod(url);
第三步:建立连接,传递数据,执行方法
client.executeMethod(httpMethod);
第四步:使用IO流获取响应报文(不止这一种方式)
POST请求的实现:
HttpURLConnection实现:
public static String doPostByHttpURLConnection(String urlPath,String postContent){
String responseContent = "";
PrintWriter pw = null;
BufferedReader br = null;
try{
//第一步:获取URL
URL url = new URL(urlPath);
//第二步:使用URL获取URLConnection
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
//第三步:设置相应的属性,包括提交模式等等
//设置提交模式
httpURLConnection.setRequestMethod("POST");
//以下两项设置是否使用URL进行输入输出,网上说POST请求这两项是必须的,其实是不严谨的,如果不打算进行输入输出,可设置为false
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
//第四步:使用IO流将数据写出
pw = new PrintWriter(httpURLConnection.getOutputStream());
//将数据写出发送
pw.write(postContent);
pw.flush();
//第五步:获取响应报文
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = null;
while((line = br.readLine())!= null){
responseContent += line;
}
}catch(Exception e){
logger.info("http post request exception error",e);
throw new RuntimeException("HTTP通信异常");
}finally{
try{
if(br != null) br.close();
}catch(Exception e){
logger.error("关闭IO异常", e);
}
}
return responseContent;
}
HttpClient实现:
public static String doPostByHttpClient(String url,String paramStr){
String result = "";
HttpClient client = null;
PostMethod postMethod = null;
try {
//第一步:获取HttpClient
client = new HttpClient();
//第二步:创建PostMethod
postMethod = new PostMethod(url);
//设置请求头,设定发送数据类型以及编码
postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//设置连接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
//30秒内未收到数据,则自动断开客户端
client.getHttpConnectionManager().getParams().setSoTimeout(30000);
//第三步:将请求数据放入请求体中
postMethod.setRequestBody(paramStr);
//第四步:方法执行
client.executeMethod(postMethod);
//第五步:获取响应报文
InputStream responseBody = postMethod.getResponseBodyAsStream();
InputStreamReader in = new InputStreamReader(responseBody, "utf-8");
BufferedReader br = new BufferedReader(in);
StringBuffer stringBuffer = new StringBuffer();
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
stringBuffer.append(inputLine);
}
in.close();
result = stringBuffer.toString().trim();
} catch (Exception e) {
logger.error("HttpsUtil.doPOST|http post request exception error ", e);
throw new RuntimeException("HTTP通信异常");
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
return result;
}
上面就是两种不同的POST请求的实现方式。实现方式上和GET请求的的套路基本一致,在这我就不赘述了。
当然,在这里POST请求的实现只是简单的传输了字符串,对于不同类型的数据传输,不仅仅需要修改Content-Type,其他的代码可能也会需要变动!在这里大家注意一下,后面我会还会继续介绍!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HTTP java