java代码实现http请求_java模拟http请求的代码实现

1、序

本文介绍两种方式:使用java自带的HttpURLConnection和第三方apache提供的HttpClient。

2、使用 HttpURLConnection 发送 HTTP 请求

Java 自带的java.net这个包中包含了很多与网络请求相关的类,这里我们就需要用到该包下的HttpURLConnection类 。

2.1、步骤详细说明

1、获取http链接对象

2、设置请求头信息

通过HttpURLConnection的setRequestProperty设置需要设置的头信息。例如有些网站会对 User-Agent 进行检查,根据这个字段来过滤一些非浏览器的请求,因此遇到这种情况,我们就要设置这个头信息,模拟成浏览器的请求。

3、设置请求的方式

HTTP 协议中定义了很多种 HTTP 请求方法:GET、POST、PUT、DELETE、OPTIONS 等等,其中最常用到的就是 GET 和 POST,因为在浏览器中大多都是使用这两种请求方法。通过连接对象的setRequestMethod()设置请求的方法。

使用 HttpURLConnection 来模拟 POST 请求和 GET 请求基本上是一样的,但是有一点不同,由于 POST 请求一般都会向服务端发送一段数据,所以 HttpURLConnection 提供了一个方法 setDoOutput(true) 来表示有数据要输出给服务端,并可以通过 getOutputStream() 得到输出流,我们将要写的数据通过这个输出流 POST 到服务端。

4、获取状态码,如果正确,则获取响应的字节输入流

从链接对象中获取到响应的字节输入流,再转换成文本内容即得到了我们想要的结果。

5、根据字节输入流获取到响应的文本内内容

2.2、get方式的代码实现

HttpURLConnection urlConnection = null;

try {

// 获取http链接对象

URL url = new URL("http://www.szlcsc.com/");

urlConnection = (HttpURLConnection) url.openConnection();

// 设置请求头相关属性,可以不用指定

urlConnection.setDoInput(true);// 默认为true,可以不用设置

urlConnection.setRequestProperty("accept", "*/*");

// 设置请求的方式

urlConnection.setRequestMethod("GET");

// 获取响应状态码,200代表正常

int responseCode = urlConnection.getResponseCode();

if (responseCode == 200) {

// 从输入的直接流中获取到文本内同

String resultContent = getContentFromInputStream(urlConnection.getInputStream());

System.out.println(resultContent);

}

} catch (Exception e) {

throw e;

} finally {

if (urlConnection != null) {

urlConnection.connect();

}

}

2.3、post方法的代码实现

HttpURLConnection urlConnection = null;

try {

// 获取http链接对象

URL url = new URL("http://www.szlcsc.com/search/global.html");

urlConnection = (HttpURLConnection) url.openConnection();

// 设置请求头相关属性,可以不用指定

urlConnection.setDoInput(true);// 默认为true,可以不用设置

urlConnection.setDoOutput(true);// 默认为false,需要传递数据一定要设置为true

urlConnection.setRequestProperty("accept", "*/*");

// 设置请求的方式

urlConnection.setRequestMethod("POST");

String postContent = "key=value";

//将请求的数据写入到输出流中

DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());

out.write(postContent.getBytes());

out.flush();

out.close();

// 获取响应状态码,200代表正常

int responseCode = urlConnection.getResponseCode();

if (responseCode == 200) {

// 从输入的直接流中获取到文本内同

String resultContent = getContentFromInputStream(urlConnection.getInputStream());

System.out.println(resultContent);

}

} catch (Exception e) {

throw e;

} finally {

if (urlConnection != null) {

urlConnection.connect();

}

}

------------------------------------------

private static String getContentFromInputStream(InputStream in) throws IOException {

String result;

StringBuffer buffer = new StringBuffer();

BufferedReader reader = null;

try {

reader = new BufferedReader(new InputStreamReader(in));

String inputLine;

while ((inputLine = reader.readLine()) != null) {

buffer.append(inputLine);

}

} catch (Exception e) {

throw e;

} finally {

if (reader != null) {

reader.close();

}

result = buffer.toString();

}

return result;

}

3、使用 HttpClient 发送 HTTP 请求

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。它相比传统的 HttpURLConnection,增加了易用性和灵活性,它不仅让客户端发送 HTTP 请求变得更容易,而且也方便了开发人员测试接口(基于 HTTP 协议的),即提高了开发的效率,也方便提高代码的健壮性。

HttpClient 对每一种 HTTP 方法都准备了一个类,GET 请求使用 HttpGet 类,POST 请求使用 HttpPost 类。

Entity 是 HttpClient 中的一个特别的概念,有着各种的 Entity ,都实现自 HttpEntity 接口,输入是一个 Entity,输出也是一个 Entity

3.1、get请求代码

//创建httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

HttpGet request =new HttpGet("http://www.szlcsc.com/");

request.setHeader("accept", "*/*");

CloseableHttpResponse response = httpclient.execute(request);

HttpEntity responseEntity = response.getEntity();

//将响应的内容转化为String

String content = EntityUtils.toString(responseEntity);

System.out.println(content);

response.close();

httpclient.close();

3,2、post请求代码

//创建httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

HttpPost request =new HttpPost("http://www.szlcsc.com/search/global.html");

request.setHeader("accept", "*/*");

//设置要提交的参数,后面的ContentType代表以表单的形式提交参数

request.setEntity(new StringEntity("key=value",ContentType.create("application/x-www-form-urlencoded")));

CloseableHttpResponse response = httpclient.execute(request);

HttpEntity responseEntity = response.getEntity();

//将响应的内容转化为String

String content = EntityUtils.toString(responseEntity);

System.out.println(content);

response.close();

httpclient.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值