java.net.SocketException:使用Spring的RestTemplate从服务器发出意外的文件结尾 [英] java.net.SocketException: Unexpected end of file from server using Spring's RestTemplate

查看:3718
本文介绍了java.net.SocketException:使用Spring的RestTemplate从服务器发出意外的文件结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了几个关于类似主题的问题/答案,但找不到适合我案例的答案。

I've already checked several questions / answers regarding similar subjects, but can't find the proper answer for my case.

我正在使用Spring的RestTemplate但是无法从第三方服务器获得响应,但有以下异常:

I'm using Spring's RestTemplate but fails to get the response from a third party server with the following exception:

Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://64.76.157.19:8283/ENAP/ProveedorExterno/v1.0/insertarUltimaPosicion":Unexpected end of file from server; nested exception is java.net.SocketException: Unexpected end of file from server
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:454)
    at cl.waypoint.integracion.GenericCallback.sendEnap(GenericCallback.java:187)
    at cl.waypoint.integracion.GenericCallback.main(GenericCallback.java:167)
Caused by: java.net.SocketException: Unexpected end of file from server
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:718)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at org.springframework.http.client.SimpleClientHttpResponse.getRawStatusCode(SimpleClientHttpResponse.java:48)
    at cl.waypoint.integracion.GenericCallback$LoggingRequestInterceptor.log(GenericCallback.java:229)
    at cl.waypoint.integracion.GenericCallback$LoggingRequestInterceptor.intercept(GenericCallback.java:216)
    at org.springframework.http.client.InterceptingClientHttpRequest$RequestExecution.execute(InterceptingClientHttpRequest.java:84)
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:69)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:551)
    ... 4 more

但是使用命令行curl发送相同的请求/标头/有效负载时似乎没有任何问题,这是它的详细输出:

But when sending the same request/headers/payload using command line curl there seems to be no problem at all, this is the verbose output of it:

*   Trying A.B.C.D...
* Connected to A.B.C.D (A.B.C.D) port 8283 (#0)
> POST /ENAP/ProveedorExterno/v1.0/insertarUltimaPosicion HTTP/1.1
> Host: A.B.C.D:8283
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Type: application/json
> Authorization: Bearer dsgfsdgf786dsfg7dsgf
> Content-Length: 567
> 
* upload completely sent off: 567 out of 567 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: POST
< Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type
< Content-Type: application/json
< Date: Wed, 27 Jul 2016 13:35:26 GMT
< Transfer-Encoding: chunked
< 
* Connection #0 to host 64.76.157.19 left intact

PS:授权令牌和服务器出于安全原因,IP地址已被更改。

PS: Authorization token and server's IP address have been changed for security reasons.

Spring似乎挂了一段时间然后抛出异常,也许它正在等待某些东西默认...内容 - 响应的长度标题?如果是这样,可以覆盖吗?

Spring seems to hang for a while and then then throw the exception, perhaps it's waiting for something by default...Content-Length header on the response? If so, can that be overriden?

异常来自以下拦截器:

class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {

        ClientHttpResponse response = execution.execute(request, body);

        log(request, body, response);

        return response;
    }

    private void log(HttpRequest request, byte[] body, ClientHttpResponse response) throws IOException {
        HttpHeaders headers = request.getHeaders();
        System.out.println("=============================");
        for (Entry<String, List<String>> header : headers.entrySet()) {
            System.out.println(header.getKey() + ": " + header.getValue());
        }
        System.out.println("=============================");
        System.out.println(new String(body));
        System.out.println(response.getRawStatusCode());
        System.out.println(response.getStatusText());

    }
}

从以下代码中使用snippet:

Which is used from the following code snippet:

private void sendEnap(String patente, String fecha, String latitud, String longitud, BigInteger sentido,
        BigInteger velocidad, int ignicion) {
    RestTemplate restTemplate = new RestTemplate();
    // set interceptors/requestFactory
    ClientHttpRequestInterceptor ri = new LoggingRequestInterceptor();
    List<ClientHttpRequestInterceptor> ris = new ArrayList<ClientHttpRequestInterceptor>();
    ris.add(ri);
    restTemplate.setInterceptors(ris);

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("Authorization", "Bearer " + ENANGAB_TOKEN);
    headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
    headers.add("User-Agent", "Waypoint");
    EnapRequest enapRequest = new EnapRequest(patente, fecha, latitud, longitud, sentido, velocidad, ignicion);
    HttpEntity<EnapRequest> request = new HttpEntity<EnapRequest>(enapRequest, headers);

    ResponseEntity<EnapResponse> response = restTemplate.exchange(ENAP_ENDPOINT, HttpMethod.POST, request,
            EnapResponse.class);
    System.out.println(response.getBody());

}

如果禁用拦截器,则会出现相同的异常,但现在这个堆栈跟踪:

If the interceptor is disabled, same exception arises but now with this stacktrace:

Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://64.76.157.19:8283/ENAP/ProveedorExterno/v1.0/insertarUltimaPosicion":Unexpected end of file from server; nested exception is java.net.SocketException: Unexpected end of file from server
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:454)
    at cl.waypoint.integracion.GenericCallback.sendEnap(GenericCallback.java:187)
    at cl.waypoint.integracion.GenericCallback.main(GenericCallback.java:167)
Caused by: java.net.SocketException: Unexpected end of file from server
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:718)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at org.springframework.http.client.SimpleClientHttpResponse.getRawStatusCode(SimpleClientHttpResponse.java:48)
    at org.springframework.http.client.AbstractClientHttpResponse.getStatusCode(AbstractClientHttpResponse.java:33)
    at org.springframework.web.client.DefaultResponseErrorHandler.getHttpStatusCode(DefaultResponseErrorHandler.java:56)
    at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:50)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:552)
    ... 4 more

以上是回复中缺少标题的另一个提示,不知道哪一个,以及如何避免这样的等待。

The above is another hint for a missing header on the response, don't know which one, and how to avoid such wait too.

任何提示都将受到赞赏

编辑:

发送的标题:

Accept: [application/json, application/*+json]
Authorization: [Bearer dsgfsdgf786dsfg7dsgf]
Content-Type: [application/json]
User-Agent: [Waypoint]
Content-Length: [567]

EnapRequest类:
package cl.waypoint.integracion;

EnapRequest class: package cl.waypoint.integracion;

import java.math.BigInteger;

import com.fasterxml.jackson.annotation.JsonProperty;

public class EnapRequest {

    @JsonProperty("token_proveedor")
    private String tokenProveedor = GenericCallback.ENANGAB_TOKEN;
    private Posicion[] posicion;

    public EnapRequest(String patente, String fecha, String latitud, String longitud, BigInteger sentido,
            BigInteger velocidad, int  ignicion) {
        posicion = new Posicion[1];
        posicion[0] = new Posicion(patente, fecha, latitud, longitud, sentido, velocidad, ignicion);
    }

    public String getTokenProveedor() {
        return tokenProveedor;
    }

    public void setTokenProveedor(String tokenProveedor) {
        this.tokenProveedor = tokenProveedor;
    }

    public Posicion[] getPosicion() {
        return posicion;
    }

    public void setPosicion(Posicion[] posicion) {
        this.posicion = posicion;
    }
}

请求正文实际上是以JSON格式发送的(与curl完全相同,在这里打印漂亮以提高阅读效果):

The request body is in fact being sent as JSON (exactly the same as with curl, pretty print here for improved reading):

{
  "posicion": [
    {
      "patente": "AB1234",
      "latitud": "-36.752752",
      "longitud": "-73.0804947",
      "direccion": "120",
      "velocidad": "65",
      "transportista": "ENANGAB",
      "sensora1": null,
      "sensora2": null,
      "sensora3": null,
      "mopo_sensord1": null,
      "mopo_sensord2": null,
      "mopo_sensord3": null,
      "mopo_sensord4": null,
      "mopo_sensord5": null,
      "mopo_sensord6": null,
      "opcional1": null,
      "opcional2": null,
      "opcional3": null,
      "opcional4": null,
      "codigo_interno": null,
      "fecha_hora": "2016-07-15T14:24:00",
      "mopo_estado": "1",
      "mopo_estado_ignicion": "1",
      "moev_numero_evento": "45"
    }
  ],
  "token_proveedor": "dsgfsdgf786dsfg7dsgf"
}

RestTemplate对象已经配置了对以下转换器的支持:

The RestTemplate object has already configured support for the following converters:

class org.springframework.http.converter.ByteArrayHttpMessageConverter
class org.springframework.http.converter.StringHttpMessageConverter
class org.springframework.http.converter.ResourceHttpMessageConverter
class org.springframework.http.converter.xml.SourceHttpMessageConverter
class org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
class org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter
class org.springframework.http.converter.json.MappingJackson2HttpMessageConverter


推荐答案

我认为这里的问题是你的请求有一个错误的数据类型,服务器无法解析无法回复。

I think the problem here is that your request has a wrong data type which server can not parse and thus can not reply.

由于您发送的是带有JSON Content-Type 标头的POST请求,您的 EnapRequest 必须是JSON编码。

Since you are sending a POST request with JSON Content-Type header, your EnapRequest must be JSON-encoded.

要做到这一点,你需要确保 EnapRequest 是一个POJO类,然后修改你的代码 sendEnap()

To do that, you need to make sure EnapRequest is a POJO class, then modify your code inside sendEnap()

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

并在类路径中包含Jackson库

and include Jackson libraries in the classpath

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.1</version>
</dependency>

这篇关于java.net.SocketException:使用Spring的RestTemplate从服务器发出意外的文件结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆