Java Http编程

HTTP编程

http编程:Java.net包
URL代表一个资源。
网址 = 协议 + 域名 + 资源文件 + 参数。

URLConnetion

  1. 获取资源的连接,创建URL对象。
  2. 通过URL的openConnections方法获得URLConnection。
  3. connect方法:建立连接。
  4. getInputStream方法,获取资源内容。

例子:
使用URLconnection获取网页数据。

package URLConnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionGetTest {

	public static void main(String[] args) {
		try {
			String str = "https://www.baidu.com";
			URL url = new URL(str);
			URLConnection connection = url.openConnection();
			connection.connect();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			String line = "";
			while((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}

HttpComponents

是一个集成的Java Http工具。实现所有的Http方法。

例子:
使用HttpComponent获取网页数据:

  1. 创建HttpClient对象。
  2. 设置一些请求的要求 RequestConfig。
  3. 创建获取网页的对象,getHttp,并加入配置信息。
  4. 执行,execute,获取数据请求。
  5. 若获取成功,输出结果。
package HttpClient;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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;

public class HttpComponents {

	public static void main(String[] args) throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000)
				.setConnectionRequestTimeout(5000)
				.setSocketTimeout(5000)
				.setRedirectsEnabled(true)
				.build();
		
		HttpGet httpGet = new HttpGet("http://www.baidu.com");
		httpGet.setConfig(requestConfig);
		
		String str = "";
		
		HttpResponse httpResponse = httpClient.execute(httpGet);
		if(httpResponse.getStatusLine().getStatusCode() == 200) {
			str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
			System.out.println(str);
		httpClient.close();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值