当前位置: 首页 > 知识库问答 >
问题:

Spring RestTemplate.Exchange在服务器端引发XML parsererror

雍俊远
2023-03-14

我在客户端使用RestTemplate.Exchange或RestTemplate.PostForObject方法,在那里我传递带有头和身份验证方法的请求。

在服务器端,与其他系统一起,它将错误抛出为

  Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
  Message: Content is not allowed in prolog.
   at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:604) ~[?:1.8.0_171]
   at org.glassfish.jersey.jaxb.internal.AbstractCollectionJaxbProvider.readFrom(AbstractCollectionJaxbProvider.java:344) ~[jersey-media-jaxb-2.24.1.jar:?]
   ERROR com.....ExceptionHandler   - Exception occurred while processing the request! javax.ws.rs.BadRequestException: HTTP 400 Bad Request
@Service("Service")
public class Service {

private static final Logger logger = LogManager.getLogger(Service.class);

@Autowired
private RestTemplate restTemplate;

@SuppressWarnings("rawtypes")
public String postRequest(String loanId, Request requestXml, Map<String, String> headersInfo) {

    HttpHeaders headers = new HttpHeaders();
//  ResponseEntity<GenericResponse<Response>>    response = null;
    Response     response = null;
//  String response = null;
    List<String> riskReductionIdList  = null;
    String riskReductionId  = null;
    String responseString = null;

    headers.setContentType(MediaType.APPLICATION_XML);
    headers.set("-External-System-ID", headersInfo.get("ExternalSystemId"));
    headers.set("-External-User-ID", headersInfo.get("ExternalUserId"));
    String plainCredentials=headersInfo.get("User") + ":" + headersInfo.get("Password");

    String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));

      byte[] encodedAuth = Base64.encodeBase64( 
              plainCredentials.getBytes(Charset.forName("US-ASCII")) );

    headers.add("Authorization", "Basic " + base64Credentials);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    StringWriter request = new StringWriter();

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Request.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
        marshaller.marshal(requestXml, request);
        logger.error(" request : " + request.toString());

    } catch (JAXBException e1) {
        logger.error("Exception happened in coverting the request for logging",e1);
    }


    HttpEntity<?> httpEntity = new HttpEntity<Object>(requestXml, headers);

    logger.error(" Request Body: " + httpEntity.getBody());
    logger.error(" Request headers: " + httpEntity.getHeaders());

    try{
    //  response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<GenericResponse<Response>>() {} );
        response = restTemplate.postForObject(url, httpEntity, Response.class);

    }catch(HttpClientErrorException ex){
        logger.error(" Error while sending data to  for loan id : " + loanId + "\n Error : "+ ex.getMessage());
        logger.error(" responseBody : " + ex.getResponseBodyAsString() + "\n statusText : "+ ex.getStatusText() + "\n statusCode : "+ ex.getStatusCode());

    }catch(HttpServerErrorException ex){
        logger.error(" Error while sending data to  for loan id : " + loanId + "\n Error : "+ ex.getMessage());
        logger.error(" responseBody : " + ex.getResponseBodyAsString() + "\n statusText : "+ ex.getStatusText() + "\n statusCode : "+ ex.getStatusCode());

    }catch(Exception ex){
        logger.error(" Error while sending data to  for loan id : " + loanId + "\n Error : "+ ex.getMessage());

    }

    responseString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> <response>     <code>0</code>     <status>SUCCESS</status>     <messages/>     <payload>        "
            + " <riskReductionIds>             <riskReductionId>10000</riskReductionId>         </riskReductionIds>     </payload> </response>";

    return riskReductionId;
}

}

共有1个答案

卫浩瀚
2023-03-14

我使用的rest模板有转换JSOn对象的代码。我创建了一个工作的restTemplate。

 类似资料:
  • 授予codeBase“file:/home/rozerin/ideaprojects/computetest/src/main/java/”{permission java.security.allpermission;}; 堆栈跟踪是; ComputeEngine异常:java.security.AccessControllException:在java.security.AccessContr

  • [dispatcherServlet]:路径为[]的上下文中servlet[dispatcherServlet]的servlet.service()引发异常[请求处理失败;] 对此有什么意见吗?

  • 如果我正确理解了服务器发送事件的原则,那么每次客户端注册到EventSource时,它实际上会打开一个到管理事件的资源的新HTTP连接。与其他HTTP请求相反,连接保持活动状态,因此专用于此客户端的服务器进程/线程将一直运行,直到客户端断开连接。 如果我们有1000个客户端使用SSE连接到一个应用程序,该怎么办?我们是否会有1000个进程/线程(做同样的事情)并发运行以处理SSE?我想我错了,但如

  • SRS不支持服务器端脚本,所谓服务器端脚本,指的是服务器可以加载外部脚本文件,解释并执行。 支持服务器脚本的服务器有FMS,语言是actionscript1.0;nginx支持的是lua。 SRS不支持服务器脚本的原因有: 不Simple:违反了SRS(Simple RTMP Server)的第一个S,支持扩展脚本,出错的几率也扩展了。 实际用处很小:我在国内知名的CDN公司工作时,所在部门就是用

  • 我正在使用windows,当socket.io发出事件时,命令提示符显示以下内容: 我想不出问题出在哪里,我做错了什么?

  • 服务器的引导共用了客户端引导的一些逻辑。 引导服务器的方法 下表显示了 ServerBootstrap 的方法 Table 9.2 Methods of ServerBootstrap‘ 名称 描述 group 设置 EventLoopGroup 用于 ServerBootstrap。这个 EventLoopGroup 提供 ServerChannel 的 I/O 并且接收 Channel cha