Java实现HTTP请求GET和POST之HTTPClient

文中使用的jar包有:commons-codec-1.9、commons-logging-1.2、httpclient-4.5.9、httpcore-4.4.11、httpmime-4.5.9

相关jar包下载可以直接去官网下载HTTPCLIENT的包

文中相关头信息写的不多,可以去上一篇文章“Java实现HTTP请求GET和POST之HttpURLConnection”中看

文中一些代码也是网上东摘西录的,这里仅作为一个模板思路参考,功能并不复杂

一、GET请求

public static void sumitGet() {
		//创建httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//创建httpGet对象
		HttpGet httpGet = new HttpGet("https://www.baidu.com");
		System.out.println("executing request " + httpGet.getURI());
		//设置头信息
		httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
		CloseableHttpResponse response = null;
		try {
			//执行Get请求
			response = httpClient.execute(httpGet);
			//获取返回的全部头信息
			Header headers[] = response.getAllHeaders();
			//获取响应实体
			HttpEntity entity = response.getEntity();
			System.out.println(response.getStatusLine());
			//处理响应实体
			if(entity != null) {
				System.out.println("长度:" + entity.getContentLength());
				System.out.println("内容:" + EntityUtils.toString(entity, "gbk"));
			}
			response.close();
			httpClient.close();
		} catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
		}
	}

 

二、POST请求,参数模拟登录

public static void submitPost() {
		//创建httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		//创建HttpPost对象
		HttpPost post = new HttpPost("https://api.douban.com/v2/book/1220562");
		//设置POST请求传递参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", "test"));
        params.add(new BasicNameValuePair("password", "12356"));
        try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
			post.setEntity(entity);
			System.out.println("executing request " + post.getURI());
			//执行请求并处理响应
			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity2 = response.getEntity();
			if (entity2 != null){
				System.out.println("响应内容:");
				System.out.println(EntityUtils.toString(entity2));
			}
			response.close();
			httpClient.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 

三、POST请求,参数格式JSON

public void test3() {
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("code", "001");
                data.put("name", "测试");

                HttpPost httpPost = new HttpPost("www.baidu.com/test2");
                httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity("",
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

四、上传文件

 public static void upload() {
    	//创建CloseableHttpClient对象
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	try {
    		//创建HttpPost对象
    		HttpPost httppost = new HttpPost("http://www.baidu.com/upFile.action");
    		//官方API解释为由文件支持的二进制正文部分
    		FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
    		//官方API解释为由字节数组支持的文本正文部分
    		StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
    		//可以用HTTP消息发送h或接收的实体
    		HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
    		httppost.setEntity(reqEntity);
    		System.out.println("executing request " + httppost.getRequestLine());
    		CloseableHttpResponse response = httpclient.execute(httppost);
    		System.out.println("----------------------------------------");
    		System.out.println(response.getStatusLine());
    		HttpEntity resEntity = response.getEntity();
    		if (resEntity != null) {
    			System.out.println("Response content length: " + resEntity.getContentLength());
    		}
    		EntityUtils.consume(resEntity);
    		response.close();
    		httpclient.close();
    	}catch (Exception e) {
    		e.printStackTrace();
		}
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值