自定義調用實現

spring httpClient實現service間的調用

get/post請求工具類
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Component
public class FapRestUtil {
private String siginKey = System.getProperties().getProperty(“fap.sigin.key”);
@Autowired
RestTemplate restTemplate;

public FapRestUtil() {
}

public JSONObject doPostByBody(String strUrl, String postString) throws Exception {
	String requestBody = postString;
	HttpHeaders headers = new HttpHeaders();
	MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
	headers.setContentType(type);
	headers.add("signature", siginKey);
	headers.add("Accept", "application/json;charset=UTF-8");
	HttpEntity<String> httpEntity = new HttpEntity(requestBody, headers);
	return (JSONObject) restTemplate.postForEntity(strUrl, httpEntity, JSONObject.class, new Object[0]).getBody();
}

public JSONObject doPostByJson(String strUrl, Map<String, Object> _params) throws Exception {
	String postString = JSON.toJSONString(_params);
	return doPostByBody(strUrl, postString);
}

public JSONObject doPostByParam(String strUrl, Map<String, String> _params) throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.add("api-version", "1.0");
	requestHeaders.add("SiginKey", siginKey);
	MultiValueMap<String, String> requestBody = new LinkedMultiValueMap();
	if (_params != null) {
		for (Map.Entry<String, String> entry : _params.entrySet()) {
			requestBody.add(entry.getKey(), entry.getValue());
		}
	}
	Object requestEntity = new HttpEntity(requestBody, requestHeaders);
	ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(strUrl, requestEntity, JSONObject.class,
			new Object[0]);
	return (JSONObject) responseEntity.getBody();
}

public String doGetByParam(String strUrl, Map<String, String> _params) {
	if (_params != null) {
		strUrl = strUrl + "?";
		for (Map.Entry<String, String> entry : _params.entrySet()) {
			strUrl = strUrl + (String) entry.getKey() + "=" + (String) entry.getValue() + "&";
		}
	}
	return (String) restTemplate.getForEntity(strUrl, String.class, new Object[0]).getBody();
}

}

發佈了29 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章