httpclient

添加架包支持:

    <dependency>
  		<groupId>org.apache.httpcomponents</groupId>
  		<artifactId>httpclient</artifactId>
  		<version>4.5.2</version>
  </dependency>

  

第一步是获取http客户端的实列,编写代码

 

package com.java.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
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 Helloword {
	public static void main(String[] args) {
		CloseableHttpClient  httpclient=HttpClients.createDefault(); //创建浏览器实列
		HttpGet httpget=new HttpGet("http://www.java1234.com"); //创建get实列
		CloseableHttpResponse response=null;
		try {
			//执行get请求
			response=httpclient.execute(httpget);
		} catch (ClientProtocolException e) { //http协议异常
			e.printStackTrace();
		} catch (IOException e) { //io异常
			e.printStackTrace();
		}
		
		//返回实体
	     HttpEntity entity=response.getEntity();
	     try {
			System.out.println("输出实体:"+EntityUtils.toString(entity,"utf-8"));
		} catch (ParseException e) { //解析异常
			e.printStackTrace();
			
		} catch (IOException e) {  //io 异常

			e.printStackTrace();
		}
		try {
			response.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

 

  

 

posted on 2019-05-18 17:48  nidegui  阅读(210)  评论(1编辑  收藏  举报