专栏首页用户画像Java HttpClient两种数据传输方式

Java HttpClient两种数据传输方式

一、HttpClient两种Post数据传输方式

package com.httpclient.util;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientUtil{

    @Test
    public void jUnitTestPost() {
        postParam();
    }
    @Test
    public void jUnitTestGet() {
        get();
    }

    /**
     * 第一种:post字节流
     * @param lineTxt
     * @throws IOException
     */
    public static void postByte(String lineTxt) throws IOException {

        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/data/store?cacheName=cache02");
        try {
            httpPost.setEntity(new ByteArrayEntity(lineTxt.getBytes("utf8")));//使用字节流传输
            httpPost.setHeader("Content-type", "text/xml;charset=utf8");//内容类型
            httpPost.setHeader("Connection", "Close");//服务端发送完数据,即关闭连接
            //HTTP 1.0规定浏览器与服务器只保持短暂的连接,浏览器的每次请求都需要与服务器建立一个TCP连接,服务器完成请求处理后立即断开TCP连接,服务器不跟踪每个客户也不记录过去的请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String rs=EntityUtils.toString(entity, "UTF-8");
                    System.out.println(rs);
                }
            } finally {
                response.close();
                return;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 第二种:post参数列表
     */
    public void postParam() {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost("https://c.api.weibo.com/2/comments/create/biz.json");
        // 创建参数队列
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("access_token", "2.00SdyOsBnp71ED50b943f4670l75U8"));
        formParams.add(new BasicNameValuePair("id", "4087614108017463"));
        formParams.add(new BasicNameValuePair("comment", "text"));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送 get请求
     */
    public void get() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet("http://www.baidu.com/");
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    System.out.println("Response content: " + EntityUtils.toString(entity));
                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、server端的数据接收方式,使用@RequestBody接收二进制字节流,使用@RequestParam接收参数列表

   @ResponseBody
   @RequestMapping(produces = "text/xml;charset=utf8", value = "/store", method = {RequestMethod.POST})
    public String commitData(@RequestParam("cacheName") String cacheName, @RequestBody String requestData) {
        JSONObject responseData = new JSONObject();
        try {
            JSONArray requestDatas = JSONArray.parseArray(requestData);
            logger.info("接受到数据:[" + requestData.length() + "]. AllData: " + requestData);
            JSONArray rs=dataStoreService.storeData(requestDatas,cacheName,configManager);
            responseData.put("rs", rs);
            responseData.put("success", true);
        } catch (Exception e) {
            logger.error("store documents exception:[" + e.getMessage() + "].", e);
            responseData.put("success", false);
            responseData.put("errorMsg", "store documents exception:[" + e.getMessage() + "].");
        } finally {
            return responseData.toJSONString();
        }
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • HttpClient 发送get请求并返回Json数据

    http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid...

    week
  • 通过 HttpClient 从指定服务器获取数据

    week
  • Python爬虫七麦APP榜单

    week
  • RestTemplate 发送 Https 请求调用

    Jacob丶
  • httpclient post发送json数组并解决json乱码问题

    shengjk1
  • 单点登录系统实现

    单点登录系统实现基于SpringBoot 今天的干货有点湿,里面夹杂着我的泪水。可能也只有代码才能让我暂时的平静。通过本章内容你将学到单点登录系统和传统登录系统...

    程序员宝库
  • HttpClient 发送Json

    shengjk1
  • 简单实现MVC模式

    View接受用户输入,并传递到Controller。 Controller统一进行处理命令,交由Model处理具体的业务。 经过处理Model更新后,通知Vie...

    端碗吹水
  • 跟着实例学习ZooKeeper的用法: 计数器

    这一篇文章我们将学习使用Curator来实现计数器。 顾名思义,计数器是用来计数的, 利用ZooKeeper可以实现一个集群共享的计数器。 只要使用相同的pat...

    用户1263954
  • 【tomcat】HTTPS访问配置 + restful调用远程HTTPS绕过验证

    由于是本地测试,请修改本地host文件C:\Windows\System32\drivers\etc\host

    肖哥哥

扫码关注云+社区

领取腾讯云代金券