您好,登錄后才能下訂單哦!
使用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));
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。