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 条评论
登录 后参与评论

相关文章

来自专栏web开发

java-生成任意格式的json数据

最近研究java的东西。之前靠着自己的摸索,实现了把java对象转成json格式的数据的功能,返回给前端。当时使用的是 JSONObject.fromObjec...

287100
来自专栏张善友的专栏

.NET 4 System.Threading.Barrier 类

在Visual Studio 2010 and .NET Framework 4 Training Kit中有个System.Threading.Barrier...

24590
来自专栏跟着阿笨一起玩NET

Webservice服务中如何保持Session

对于Web Service,每个方法的调用都会启动一个Session,可以用下面的方法来使多个调用在同一个Session里

43110
来自专栏Java成神之路

Java微信公众平台开发_06_素材管理

30820
来自专栏GreenLeaves

C#核编之System.Environment类

      在前面的例子中用来了Environment.GetCommandLineArgs()这个方法,这个方法就是获取用户的命令行输入,是Environme...

25970
来自专栏数据分析

C# 6.0 功能预览 (二)

在Language Feature Status上面看到,其实更新的并不是特别多,为了不会误导看了C# 6.0 功能预览 (一)的园友,现在把官方的更新列表拿了...

32550
来自专栏大内老A

开发自己的Data Access Application Block[上篇]

经常在网上看到对ORM的讨论沸沸扬扬,我也来凑个热闹,谈谈我写的一个ORM。最近在做一项工作,把我们经常用到的一些业务逻辑抽象出来,写成一个个的Applicat...

19580
来自专栏函数式编程语言及工具

Akka(36): Http:Client-side-Api,Client-Connections

   Akka-http的客户端Api应该是以HttpRequest操作为主轴的网上消息交换模式编程工具。我们知道:Akka-http是搭建在Akka-stre...

26990
来自专栏草根专栏

使用两种方法让 ASP.NET Core 实现遵循 HATEOAS 结构的 RESTful API

HATEOAS(Hypermedia as the engine of application state)是 REST 架构风格中最复杂的约束,也是构建成熟 ...

588110
来自专栏Java职业技术分享

java爬虫带你爬天爬地爬人生,爬新浪

HttpClient是Apache Jakarta Common下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持...

17250

扫码关注云+社区

领取腾讯云代金券