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

来源:互联网 发布:java老版经典手机游戏 编辑:程序博客网 时间:2024/05/22 14:17

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,其他的代码可能也会需要变动!在这里大家注意一下,后面我会还会继续介绍!

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 初中分到差班怎么办 高中分到平行班怎么办 夏季皮肤起皮屑怎么办 皮肤局部起皮屑怎么办 嘴角两边起皮屑怎么办 嘴角旁边起皮屑怎么办 春季脸上起皮怎么办 手上起白皮屑怎么办 手背起皮干燥怎么办 不会读的英语怎么办 中学生不准时回家怎么办 汽车轮胎锈住了怎么办 新轮胎不好装怎么办 学it找不到工作怎么办 血液里有微生物怎么办 机械硬盘不显示怎么办 六安建筑机械租赁公司怎么办 别墅楼梯太陡怎么办 不锈钢楼梯太陡怎么办 真皮白色鞋脏了怎么办 白色牛皮包脏了怎么办 白色羊皮鞋脏了怎么办 白色真皮染色了怎么办 白色漆皮鞋脏了怎么办 对鉴定结果不服怎么办 洗衣机入水口堵塞怎么办 华科办临时饭卡怎么办 血浆乳酸测定高怎么办 olay大红瓶过敏怎么办 饥一顿饱一顿怎么办 朝鲜人向去韩国怎么办? 我是超级大方脸怎么办 被精神病砍断四根筋怎么办 40小时不睡觉怎么办 边防转业军人安置不好怎么办 转业军人孩子读书怎么办玉环 军官证丢了怎么办 飞行学员停飞了怎么办 丹东港债券违约怎么办 对村党支部贿选怎么办 马自达2油耗高怎么办