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

作者:这很周锐 时间:2022-10-29 06:45:51 

这篇文章主要介绍了如何使用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));

来源:https://www.cnblogs.com/zrboke/p/11834532.html

标签:httpclient,发送,java,对象,服务器
0
投稿

猜你喜欢

  • Android布局之帧布局FrameLayout详解

    2023-08-07 04:45:29
  • Springboot Vue可配置调度任务实现示例详解

    2023-11-09 03:33:19
  • Android闹钟机制实现定时任务功能

    2021-08-06 07:36:03
  • WPF自动隐藏的消息框的实例代码

    2023-09-11 09:52:36
  • Java中OAuth2.0第三方授权原理与实战

    2021-09-27 01:48:57
  • C#设计模式之工厂模式

    2023-07-10 13:43:33
  • c#实现ini文件读写类分享

    2022-08-31 09:47:48
  • SpringBoot项目启动时如何读取配置以及初始化资源

    2021-11-19 04:04:11
  • java8 forEach结合Lambda表达式遍历 List操作

    2021-07-04 07:22:55
  • C#中的==运算符

    2022-08-19 21:50:56
  • StringBuilder为什么线程不安全深入讲解

    2023-01-24 01:52:55
  • 简单讲解Android开发中触摸和点击事件的相关编程方法

    2023-03-30 12:29:10
  • WinForm拖拽控件生成副本的解决方法

    2022-07-02 13:28:26
  • Spring Boot和Thymeleaf整合结合JPA实现分页效果(实例代码)

    2023-11-25 07:05:15
  • 第一次编写Java流布局图形界面

    2023-10-13 08:27:11
  • spring boot org.junit.jupiter.api不存在的解决

    2023-07-11 18:34:16
  • Android实现实时通信示例

    2022-12-27 00:59:55
  • Java中使用websocket实现在线聊天功能

    2023-01-03 22:07:20
  • IntelliJ IDEA 2022.2 正式发布新功能体验

    2021-08-14 02:47:33
  • Servlet 过滤器详细介绍

    2021-10-21 13:51:57
  • asp之家 软件编程 m.aspxhome.com