前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java HttpClient两种数据传输方式

Java HttpClient两种数据传输方式

作者头像
week
发布2018-08-24 15:34:37
3.4K0
发布2018-08-24 15:34:37
举报
文章被收录于专栏:用户画像用户画像

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

代码语言:javascript
复制
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接收参数列表

代码语言:javascript
复制
   @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();
        }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年04月17日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档