1.新建service文件 http.service.ts
2.引入 http相关 文件
import { HttpClient, HttpContext, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
3.定义请求方法
public getByJson<T>(serviceType: string, reqPath: string, params?: HttpParams): Observable<T | ErrorRs> {
return this.http
.get<T>(this.url(serviceType, reqPath), this.options_external(HttpAssist.CONTENT_TYPE_JSON, params))
.pipe(
map((res: any) => {
return res.body;
}),
catchError(this.handleError(serviceType, 'Request data to webservice by GET method failed.'))
);
}
public postByJson<T>(serviceType: string, reqPath: string, body: any): Observable<T | ErrorRs> {
return this.http
.post<T>(this.url(serviceType, reqPath), body, this.options_external(HttpAssist.CONTENT_TYPE_JSON))
.pipe(
map((res: any) => {
return res.body;
}),
catchError(this.handleError(serviceType, 'Request data to webservice by POST method failed.'))
);
}
注: 自封的方法,有多少参数自己定义,需要注意的点为,
get<T>(路径参数,请求头参数) 请求头参数(请求封装类型,路径参数)
post<T>(路径参数,params参数,请求头参数) 请求头参数(请求封装类型)
封装类型如 'application/json'
.pipe中可设置,请求返回结果,以及异常处理
请求头方法如下
public options_external(contentType: string, params?: HttpParams) {
const responseObject: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'response';
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType?: any;
withCredentials?: boolean;
} = {
observe: 'response',
responseType: 'json'
};
let userToken = this.appStorageService.getStoredSessionStorageKey(StorageKey.Token);
if (userToken == null && userToken == undefined) {
userToken = "";
}
let userChannel = this.appStorageService.getStoredSessionStorageKey(StorageKey.Channel);
if (userChannel == null && userChannel == undefined) {
userChannel = "";
}
let deviceID = this.appStorageService.getStoredSessionStorageKey("plateform");
if (deviceID == null && deviceID == undefined) {
deviceID = "";
}
const headerOpts = this.headers(contentType, userToken, userChannel, deviceID, this.socureSDKService.getSessionId());
if (headerOpts) {
responseObject.headers = headerOpts;
}
if (params) {
responseObject.params = params;
}
return responseObject;
}
定义请求头参数responseObject 初始化类型,以及初始值, 拿到要放入请求头中的变量值,
走headers方法,将headers属性值拿到, 将headers属性值,和params路径参数属性值,放入responseObject请求头参数中,返回。
headers方法代码
private headers(contentType: string, userToken: string, userChannel: string, deviceID: string, socureSdkSessionId?: string): HttpHeaders {
const headerMap = new StringMap();
if ('application/json' === contentType) {
headerMap['Content-Type'] = 'application/json';
}
headerMap[HttpAssist.USER_TOKEN] = userToken;
headerMap[HttpAssist.USER_Channel] = userChannel;
headerMap[HttpAssist.DEVICE_ID] = deviceID;
if (socureSdkSessionId) {
headerMap[HttpAssist.SOCURESDK_SESSIONID] = socureSdkSessionId;
}
const headerOpts: HttpHeaders = new HttpHeaders(headerMap);
return headerOpts;
}
实际使用
this.httpService.postByJson('payment', this.sendEmail, {
"user_id": this.userID,
"type": "payment",
"email": this.emailValue
}).subscribe( u => {},error => {} );
this.httpService.getByJson('payment', this.getEnduserDetails + "?enduser_id=" + this.endUserID).subscribe( u => {},error => {} );
因为有多个服务,所以在请求中加入了,新的变量,第一个变量payment用来区分走哪一个服务的路径。
当请求类型为blob类型时,仅需替换请求头参数responseObject初始定义设置即可
const responseObject: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
responseType: 'blob';
} = {
responseType: 'blob'
};
java后台接收以及设置请求头中的参数
@Override
public boolean preHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object object) {
if (httpServletRequest.getMethod().equals("OPTIONS")) {
return true;
}
//判断token是否不存在
String token = httpServletRequest.getHeader("X-Token");
if (null == token || "".equals(token.trim())) {
throw new SecurityAuthException(propertiesUtils.get("current_request_is_unauthorized"));
}
try {
//判断请求时间是否过期
Claims parseToken = tokenUtil.parseToken(token);
if (parseToken.getExpiration().getTime() < System.currentTimeMillis()) {
throw new SecurityAuthException(propertiesUtils.get("token_expired"));
}
String userId = parseToken.get("user_id", String.class);
String newToken = tokenUtil.generateToken(userId);
//设置请求头参数
httpServletResponse.setHeader("Access-Control-Expose-Headers", "X-Token");
httpServletResponse.addHeader("X-Token", newToken);
} catch (SecurityAuthException exception) {
throw new SecurityAuthException("preHandle", propertiesUtils.get("token_expired"), exception);
} catch (ExpiredJwtException exception) {
throw new SecurityAuthException("preHandle", propertiesUtils.get("token_expired"), exception);
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
//这里的内容也不能少。设置请求头
if (request.getMethod().equals("OPTIONS")) {
return;
}
response.setHeader("Access-Control-Allow-Headers", "*");
}
JAVA后台http请求
package com.xx.xx.creditcard.service.impl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xx.xx.creditcard.exception.BusinessException;
import com.xx.xx.creditcard.exception.ExceptionResultData;
import com.xx.xx.creditcard.exception.SystemException;
import com.xx.xx.creditcard.utils.NullOrEmptyStringAdapterFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import javax.validation.ValidationException;
@Slf4j
public class BaseService {
@Autowired
protected RestTemplate restTemplate;
protected Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new NullOrEmptyStringAdapterFactory())
.create();
/**
* Make a post request in json mode.
*
* @param url
* @param body
* @param clazz<T>
* @return <T> T
*/
public <T> T postByJson(String url, String body, Class<T> clazz) {
log.info("Post request url = " + url);
ResponseEntity<T> apiResponse = null;
try {
apiResponse = restTemplate.exchange(
url
, HttpMethod.POST
, getHttpEntity(body)
, clazz);
} catch (HttpStatusCodeException e) {
handlerException(e);
}
assert apiResponse != null;
return apiResponse.getBody();
}
/**
* Make a get request in json mode.
*
* @param url
* @param body
* @param responseType<T>
* @return <T> T
*/
public <T> T getByJson(String url, String body, ParameterizedTypeReference<T> responseType) {
log.info("Get request url = " + url);
ResponseEntity<T> apiResponse = null;
try {
apiResponse = restTemplate.exchange(
url
, HttpMethod.GET
, getHttpEntity(body)
, responseType);
} catch (HttpStatusCodeException e) {
handlerException(e);
}
assert apiResponse != null;
return apiResponse.getBody();
}
/**
* Make a get request in json mode.
*
* @param url
* @param body
* @param clazz<T>
* @return <T> T
*/
public <T> T getByJson(String url, String body, Class<T> clazz) {
log.info("Get request url = " + url);
ResponseEntity<T> apiResponse = null;
try {
apiResponse = restTemplate.exchange(
url
, HttpMethod.GET
, getHttpEntity(body)
, clazz);
} catch (HttpStatusCodeException e) {
handlerException(e);
}
assert apiResponse != null;
return apiResponse.getBody();
}
/**
* Make a put request in json mode.
*
* @param url
* @param body
* @param clazz<T>
* @return <T> T
*/
public <T> T putByJson(String url, String body, Class<T> clazz) {
log.info("Put request url = " + url);
ResponseEntity<T> apiResponse = null;
try {
apiResponse = restTemplate.exchange(
url
, HttpMethod.PUT
, getHttpEntity(body)
, clazz);
} catch (HttpStatusCodeException e) {
handlerException(e);
}
assert apiResponse != null;
return apiResponse.getBody();
}
/**
* Get http entity.
*
* @param body
* @return HttpEntity<Object>
*/
private HttpEntity<Object> getHttpEntity(String body) {
HttpEntity<Object> httpEntity;
if (TextUtils.isEmpty(body)) {
httpEntity = new HttpEntity<>(getHttpHeaders());
} else {
httpEntity = new HttpEntity<>(body, getHttpHeaders());
}
return httpEntity;
}
/**
* Get http headers.
*
* @return HttpHeaders
*/
private HttpHeaders getHttpHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
httpHeaders.setContentType(type);
return httpHeaders;
}
/**
* Handler exception.
*
* @param e
* @return
*/
public void handlerException(HttpStatusCodeException e) {
ExceptionResultData exceptionResultData = gson.fromJson(e.getResponseBodyAsString(), ExceptionResultData.class);
switch (exceptionResultData.getErrorCode()) {
case 400:
throw new ValidationException(exceptionResultData.getMessage());
case 500:
if ("BusinessException".equals(exceptionResultData.getErrorType())) {
throw new BusinessException(exceptionResultData.getMessage());
} else if ("Exception".equals(exceptionResultData.getErrorType())) {
throw new RuntimeException(exceptionResultData.getMessage());
} else if ("SystemException".equals(exceptionResultData.getErrorType())) {
throw new SystemException(exceptionResultData.getMessage());
}
default:
throw new RuntimeException(exceptionResultData.getMessage());
}
}
}
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
public class NullOrEmptyStringAdapterFactory implements TypeAdapterFactory {
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<T> rawType = (Class<T>) type.getRawType();
if (rawType != String.class) {
return null;
}
return (TypeAdapter<T>) new StringEmptyAdapter();
}
}
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* Public return result.
*
*/
@Data
@Schema(name = "ExceptionResultData", description = "error return object")
public class ExceptionResultData<T> {
@Schema(defaultValue = "400", name = "errorCode", description = "errorCode")
private int errorCode;
@Schema(name = "message", description = "message")
private String message; // response message
@Schema(name = "errorType", description = "errorType")
private String errorType;
/**
* @param code
* @param message
* @param errorType
* @param <T>
* @return
*/
public static <T> ExceptionResultData<T> exception(int code, String message, String errorType) {
ExceptionResultData<T> exceptionResultData = new ExceptionResultData<>();
exceptionResultData.setErrorCode(code);
exceptionResultData.setMessage(message);
exceptionResultData.setErrorType(errorType);
return exceptionResultData;
}
}
实际使用
fetchEndUserResponses = getByJson(url, "", FetchEndUserResponses.class);
String body = gson.toJson(kycCheckRequest);
kycCheckResponses = postByJson(url, body, KYCCheckResponses.class);