使用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工具類

  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));



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM