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

 更新时间:2019年11月12日 14:35:51   作者:这很周锐  
这篇文章主要介绍了如何使用HttpClient发送java对象到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

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

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
</dependency>

二、创建JavaBean实体类对象

public class FulFillMent implements BaseModel {
  /**
   * shopify内部订单物理位置ID
   */
  private Long location_id;
  /**
   * 运单号
   */
  private String tracking_number;
  /**
   * 快递公司
   */
  private String tracking_company;
  /**
   * shopify平台内部商品id
   */
  private List<LineItem> 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<LineItem> getLine_items() {
    return line_items;
  }
  public void setLine_items(List<LineItem> 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));

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

相关文章

  • Java ArrayList实现班级信息管理系统

    Java ArrayList实现班级信息管理系统

    这篇文章主要为大家详细介绍了Java ArrayList实现班级信息管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • SpringBoot中异常处理实战记录

    SpringBoot中异常处理实战记录

    在我们实际项目开放中经常需要我们处理很多的异常,如何在spring boot项目里面实现异常处理呢,下面这篇文章主要给大家介绍了关于SpringBoot中异常处理的相关资料,需要的朋友可以参考下
    2022-05-05
  • java实现人民币大小写转换方法分享

    java实现人民币大小写转换方法分享

    本文介绍java人民币数字大小写转换方法,代码中有注释,大家直接看代码吧
    2014-01-01
  • SpringBoot disruptor高性能队列使用

    SpringBoot disruptor高性能队列使用

    这篇文章主要介绍了SpringBoot disruptor高性能队列使用,Disruptor是英国外汇交易公司LMAX开发的一个高性能队列,研发的初衷是解决内存队列的延迟问题
    2023-02-02
  • Java 在线考试云平台的实现

    Java 在线考试云平台的实现

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+vue+springboot+mysql+maven实现一个前端vue后台java微服务的在线考试系统,大家可以在过程中查缺补漏,提升水平
    2021-11-11
  • 用JAVA实现单链表,检测字符串是否是回文串

    用JAVA实现单链表,检测字符串是否是回文串

    这篇文章主要介绍了使用JAVA实现单链表,检测字符串是否是回文串,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2020-11-11
  • IDEA使用Maven创建module出现Ignored pom.xml问题及解决

    IDEA使用Maven创建module出现Ignored pom.xml问题及解决

    这篇文章主要介绍了IDEA使用Maven创建module出现Ignored pom.xml问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • 详解Spring Boot 项目部署到heroku爬坑

    详解Spring Boot 项目部署到heroku爬坑

    这篇文章主要介绍了详解Spring Boot 项目部署到heroku爬坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • LCN分布式事务解决方案详解

    LCN分布式事务解决方案详解

    这篇文章主要介绍了LCN分布式事务解决方案详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Spring计划任务用法实例详解

    Spring计划任务用法实例详解

    这篇文章主要介绍了Spring计划任务用法,结合实例形式详细分析了spring计划任务相关原理、配置、使用方法及操作注意事项,需要的朋友可以参考下
    2019-11-11

最新评论