【问题标题】:HttpRequest from app engine endpoint. Connection reset来自应用引擎端点的 HttpRequest。连接重置
【发布时间】:2023-04-09 05:43:02
【问题描述】:

我正在尝试从 APP Engine 端点发送 HTTP 请求,从 Postman 的实验中我知道结果很大,并且请求通常需要大约一分钟。

这是我的代码:

void testRequest() {
    String test = getConnectionString();
    URL url = new URL(YARDI_URL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/xml");
    connection.setConnectTimeout(1000000);
    OutputStream os = connection.getOutputStream();
    PrintWriter p = new PrintWriter(os);
    p.print(test);
    p.close();

    YardiResponse response = new 
    YardiResponse(connection.getInputStream().toString());

    System.out.println(response.getResponse());
    connection.disconnect();
}

我遇到两个错误,

第一个是:java.net.ProtocolException: Cannot write output after reading input.

很长一段时间后,我收到了java.net.SocketException: Connection reset 消息。

很明显,我对 Steam 以及我发送它们的方式处理不当。

【问题讨论】:

    标签: java http inputstream outputstream


    【解决方案1】:

    我强烈推荐 http-request 基于 apache http api。

    private static final HttpRequest<String.class> HTTP_REQUEST = 
          HttpRequestBuilder.createPost(YARDI_URL, String.class)
               .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
               .contentTypeOfBody(ContentType.TEXT_XML)
               .connectTimeout(someIntValue)
               .socketTimeOut(someIntValue)
               .connectionRequestTimeout(someIntValue).
               .build();
    
    void testRequest() {
       ResponseHadler<String> yardiHandler = HTTP_REQUEST.executeWithBody(yourXml);
    
       int statusCode = yardiHandler.getStatusCode();
       String content = yardiHandler.get(); //returns response body as String in this case
    }
    

    注意:我推荐查看 connectTimeoutsocketTimeOutconnectionRequestTimeout 方法的 javadocs。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      相关资源
      最近更新 更多