1. 程式人生 > 程式設計 >如何使用HttpClient傳送java物件到伺服器

如何使用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:%[email protected]/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));

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。