http 簡單呼叫第三方介面
阿新 • • 發佈:2018-12-31
僅做記錄,注意post請求亂碼問題~~
maven依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
package com.tianan.delivery; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import com.tianan.delivery.common.util.XMLUtil; import com.tianan.delivery.kernel.vo.httpClient.DeliveryRequest; import com.tianan.delivery.kernel.vo.httpClient.DeliveryRequestBody; import com.tianan.delivery.kernel.vo.httpClient.DeliveryRequestHead; public class HttpClientDemo { public static void main(String[] args) throws Exception { // 封裝頭資訊和主體 DeliveryRequest deliveryRequest = new DeliveryRequest(); DeliveryRequestHead deliveryRequestHead = new DeliveryRequestHead(); deliveryRequestHead.setApplyNo("8666666666666666666666"); deliveryRequestHead.setApplyTime("2016-03-16 10:33:24"); deliveryRequestHead.setApplyType("V003"); deliveryRequestHead.setSIGN("XXXXXXXXXXXXXXXXXXXXXX"); DeliveryRequestBody deliveryRequestBody = new DeliveryRequestBody(); deliveryRequestBody.setProposalNo("8666666666666666666666"); deliveryRequestBody.setCustomerSource("010101"); deliveryRequest.setDeliveryRequestHead(deliveryRequestHead); deliveryRequest.setDeliveryRequestBody(deliveryRequestBody); // 轉化為對應XML檔案 // String responseMessage = XMLUtil.toXml(deliveryRequest); // 直接copy現成xml檔案做測試 String responseMessage = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><root><head><applyNo>8666666666666666666666</applyNo><applyTime>2015-10-15 14:23:55</applyTime><applyType>V003</applyType><SIGN>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</SIGN></head><body><proposalNo>8666666666666666666666</proposalNo><customerSource>010101</customerSource></body></root>"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://localhost:8082/delivery2/delivery/deliveryFind"); httpPost.addHeader("content-type", "text/xml"); // 注意設定編碼 StringEntity entity = new StringEntity(responseMessage, "UTF-8"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); String response = EntityUtils.toString(httpResponse.getEntity()); System.out.println("************"); System.out.println(response); } }