码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-11-11 14:22:01      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:util   方式   private   tst   tle   物理   字符集   int   create   

    一、首先导入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工具类

  1 package com.glbpay.ivs.common.util.https;
  2 import com.alibaba.fastjson.JSON;
  3 import org.apache.http.HttpEntity;
  4 
  5 import java.io.InputStream;
  6 import java.io.OutputStream;
  7 import org.apache.http.client.ClientProtocolException;
  8 import org.apache.http.client.methods.CloseableHttpResponse;
  9 import org.apache.http.client.methods.HttpPost;
 10 import org.apache.http.entity.StringEntity;
 11 import org.apache.http.impl.client.CloseableHttpClient;
 12 import org.apache.http.impl.client.HttpClientBuilder;
 13 import org.apache.http.util.EntityUtils;
 14 import java.io.IOException;
 15 import java.net.HttpURLConnection;
 16 import java.net.MalformedURLException;
 17 import java.net.URL;
 18 
 19 
 20 public class NewHttpClient {
 21     public static String doPost(String url, Object myclass) {
 22         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 23         HttpPost posturl = new HttpPost(url);
 24         String result = null;
 25         String jsonSting = JSON.toJSONString(myclass);
 26         StringEntity entity = new StringEntity(jsonSting, "UTF-8");
 27         posturl.setEntity(entity);
 28         posturl.setHeader("Content-Type", "application/json;charset=utf8");
 29         // 响应模型
 30         CloseableHttpResponse response = null;
 31         try {
 32             // 由客户端执行(发送)Post请求
 33 +6            response = httpClient.execute(posturl);
 34             // 从响应模型中获取响应实体
 35             HttpEntity responseEntity = response.getEntity();
 36 
 37             System.out.println("响应状态为:" + response.getStatusLine());
 38             if (responseEntity != null) {
 39                 System.out.println("响应内容长度为:" + responseEntity.getContentLength());
 40                 System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
 41                 return EntityUtils.toString(responseEntity);
 42             }
 43         } catch (ClientProtocolException e) {
 44             e.printStackTrace();
 45         } catch (Exception e) {
 46             e.printStackTrace();
 47         } finally {
 48             try {
 49                 // 释放资源
 50                 if (httpClient != null) {
 51                     httpClient.close();
 52                 }
 53                 if (response != null) {
 54                     response.close();
 55                 }
 56             } catch (IOException e) {
 57                 e.printStackTrace();
 58             }
 59         }
 60       return null;
 61     }
 62     public static String dourl(String url,Object clzz){
 63         try {
 64             String jsonString = JSON.toJSONString(clzz);
 65             URL url1 = new URL(url);
 66             HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
 67             //设置允许输出
 68             conn.setDoOutput(true);
 69             //设置允许输入
 70             conn.setDoInput(true);
 71             //设置不用缓存
 72             conn.setUseCaches(false);
 73             conn.setRequestMethod("POST");
 74 
 75             //设置传递方式
 76             conn.setRequestProperty("contentType", "application/json");
 77             // 设置维持长连接
 78             conn.setRequestProperty("Connection", "Keep-Alive");
 79             // 设置文件字符集:
 80             conn.setRequestProperty("Charset", "UTF-8");
 81             //开始请求
 82             byte[] bytes = jsonString.toString().getBytes();
 83             //写流
 84             OutputStream stream = conn.getOutputStream();
 85             stream.write(bytes);
 86             stream.flush();
 87             stream.close();
 88             int resultCode=conn.getResponseCode();
 89               if(conn.getResponseCode()==200){
 90               InputStream inputStream = conn.getInputStream();
 91               byte[] bytes1 = new byte[inputStream.available()];
 92               inputStream.read(bytes1);
 93               //转字符串
 94               String s = new String(bytes);
 95               System.out.println(s);
 96                   return s;
 97           }else {
 98                   //获取响应内容
 99                   int code = conn.getResponseCode();
100                   String responseMessage = conn.getResponseMessage();
101                   System.out.println(code);
102                   String s = String.valueOf(code);
103                   return "响应状态码是:"+s+"响应内容是:======="+responseMessage;
104               }
105         } catch (MalformedURLException e) {
106             e.printStackTrace();
107         } catch (IOException e) {
108             e.printStackTrace();
109         }
110                   return null;
111     }
112 
113 }

 

三、开始调用
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));


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

标签:util   方式   private   tst   tle   物理   字符集   int   create   

原文地址:https://www.cnblogs.com/zrboke/p/11834532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!