热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用HttpClient发送java对象到服务器

这篇文章主要介绍了如何使用HttpClient发送java对象到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要

这篇文章主要介绍了如何使用HttpClient发送java对象到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

 一、首先导入apache依赖的pom文件包


  org.apache.httpcomponents
  httpclient

二、创建JavaBean实体类对象

public class FulFillMent implements BaseModel {
  /**
   * shopify内部订单物理位置ID
   */
  private Long location_id;
  /**
   * 运单号
   */
  private String tracking_number;
  /**
   * 快递公司
   */
  private String tracking_company;
  /**
   * shopify平台内部商品id
   */
  private List line_items;
  public Long getLocation_id() {
    return location_id;
  }
  public void setLocation_id(Long location_id) {
    this.location_id = location_id;
  }
  public String getTracking_number() {
    return tracking_number;
  }

  public void setTracking_number(String tracking_number) {
    this.tracking_number = tracking_number;
  }

  public String getTracking_company() {
    return tracking_company;
  }

  public void setTracking_company(String tracking_company) {
    this.tracking_company = tracking_company;
  }
  public List getLine_items() {
    return line_items;
  }
  public void setLine_items(List line_items) {
    this.line_items = line_items;
  }
}

三、这里封装一个上传到服务器的Utils工具类

package com.glbpay.ivs.common.util.https;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;

import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class NewHttpClient {
  public static String doPost(String url, Object myclass) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost posturl = new HttpPost(url);
    String result = null;
    String jsOnSting= JSON.toJSONString(myclass);
    StringEntity entity = new StringEntity(jsonSting, "UTF-8");
    posturl.setEntity(entity);
    posturl.setHeader("Content-Type", "application/json;charset=utf8");
    // 响应模型
    CloseableHttpResponse respOnse= null;
    try {
      // 由客户端执行(发送)Post请求
+6      respOnse= httpClient.execute(posturl);
      // 从响应模型中获取响应实体
      HttpEntity respOnseEntity= response.getEntity();

      System.out.println("响应状态为:" + response.getStatusLine());
      if (responseEntity != null) {
        System.out.println("响应内容长度为:" + responseEntity.getContentLength());
        System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
        return EntityUtils.toString(responseEntity);
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        // 释放资源
        if (httpClient != null) {
          httpClient.close();
        }
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
   return null;
  }
  public static String dourl(String url,Object clzz){
    try {
      String jsOnString= JSON.toJSONString(clzz);
      URL url1 = new URL(url);
      HttpURLConnection cOnn= (HttpURLConnection) url1.openConnection();
      //设置允许输出
      conn.setDoOutput(true);
      //设置允许输入
      conn.setDoInput(true);
      //设置不用缓存
      conn.setUseCaches(false);
      conn.setRequestMethod("POST");

      //设置传递方式
      conn.setRequestProperty("contentType", "application/json");
      // 设置维持长连接
      conn.setRequestProperty("Connection", "Keep-Alive");
      // 设置文件字符集:
      conn.setRequestProperty("Charset", "UTF-8");
      //开始请求
      byte[] bytes = jsonString.toString().getBytes();
      //写流
      OutputStream stream = conn.getOutputStream();
      stream.write(bytes);
      stream.flush();
      stream.close();
      int resultCode=conn.getResponseCode();
       if(conn.getResponseCode()==200){
       InputStream inputStream = conn.getInputStream();
       byte[] bytes1 = new byte[inputStream.available()];
       inputStream.read(bytes1);
       //转字符串
       String s = new String(bytes);
       System.out.println(s);
         return s;
     }else {
         //获取响应内容
         int code = conn.getResponseCode();
         String respOnseMessage= conn.getResponseMessage();
         System.out.println(code);
         String s = String.valueOf(code);
         return "响应状态码是:"+s+"响应内容是:======="+responseMessage;
       }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
         return null;
  }

}

开始调用

FulFillMentModel fulFillMentModel = new FulFillMentModel();
FulFillMent fulfillment = new FulFillMent();
fulfillment.setLocation_id(order.getLocationId());
fulfillment.setTracking_number(order.getTrackingNo());
fulfillment.setTracking_company(order.getChannelCode());
fulfillment.setLine_items(lineItemList);
fulFillMentModel.setFulfillment(fulfillment);
String url = String.format("https://%s:%s@stuushop-com.myshopify.com/admin/api/2019-07/orders/%s/fulfillments.json", settingModel.getAppKey(), settingModel.getPassword(), order.getLastOrderId());
logger.info("shopify平台请求地址:{},请求数据:{}", url, JsonUtils.bean2json(fulFillMentModel));
String s = NewHttpClient.doPost(url,fulFillMentModel);
logger.info("shopify平台返回数据:{}", JsonUtils.bean2json(s));

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程笔记。


推荐阅读
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文介绍了Perl的测试框架Test::Base,它是一个数据驱动的测试框架,可以自动进行单元测试,省去手工编写测试程序的麻烦。与Test::More完全兼容,使用方法简单。以plural函数为例,展示了Test::Base的使用方法。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • Node.js学习笔记(一)package.json及cnpm
    本文介绍了Node.js中包的概念,以及如何使用包来统一管理具有相互依赖关系的模块。同时还介绍了NPM(Node Package Manager)的基本介绍和使用方法,以及如何通过NPM下载第三方模块。 ... [详细]
  • HttpClient作为官方推荐的http客户端,相比之前的WebClient和WebRequest好用了很多,但默认无法为每个请求单独设置超时,只能给HttpClient设置默认 ... [详细]
  • 本文介绍了使用postman进行接口测试的方法,以测试用户管理模块为例。首先需要下载并安装postman,然后创建基本的请求并填写用户名密码进行登录测试。接下来可以进行用户查询和新增的测试。在新增时,可以进行异常测试,包括用户名超长和输入特殊字符的情况。通过测试发现后台没有对参数长度和特殊字符进行检查和过滤。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • Gitlab接入公司内部单点登录的安装和配置教程
    本文介绍了如何将公司内部的Gitlab系统接入单点登录服务,并提供了安装和配置的详细教程。通过使用oauth2协议,将原有的各子系统的独立登录统一迁移至单点登录。文章包括Gitlab的安装环境、版本号、编辑配置文件的步骤,并解决了在迁移过程中可能遇到的问题。 ... [详细]
author-avatar
椰子
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有