java - GlassFish 3 - GET/POST/PUT/DELETE 上的 400 错误请求

标签 java rest groovy glassfish-3

在我的脚本中,我创建了一个小型且简单的 REST 客户端。脚本本身是一个原型(prototype),因此代码不具有“生产值(value)” - 因此请忽略惰性 catch 表达式等。

有两种类型的服务器包含我从中获取数据的 REST 服务; WildFly 8.2.0 或 GlassFish 3.1.2.2。这里的问题是:我的 REST 客户端可以很好地从 Wildfly 服务器获取数据,但 GlassFish 服务器对于任何请求都会返回 HTTP 400 错误请求

我可以通过 Web 浏览器访问两台服务器的 REST 服务,因此我知道它们都工作正常。我什至可以通过套接字与两台服务器进行原始连接,并且它们会使用正确的数据进行响应。

那么,GlassFish 不接受请求的原因可能是什么?

套接字连接(用于测试)

import java.net.Socket;

Socket s = new Socket("localhost", 8080);
String t = "GET /rest/appointment/appointments/search/?fromDate=2016-11-21&branchId=3 HTTP/1.1\nhost: localhost:8080\nAuthorization: Basic base64encodedUsername:PasswordHere\n\n"
OutputStream out = s.getOutputStream();
out.write(t.getBytes());

InputStream inn = s.getInputStream();
Scanner scan = new Scanner(inn);
String line;
while ((line = scan.nextLine()) != null) {
    println line;
}
s.close();

REST 客户端代码:

import groovy.json.JsonSlurper;
import javax.xml.bind.DatatypeConverter;


/*
REST-client (a very simple one)
*/
public class RESTclient {
  public static Object get(URL url, Map<String, String> headers) {
    return http(url, "GET", null, headers);
  }
  public static Object post(URL url, String data, Map<String, String> headers) {
    return http(url, "POST", data, headers);
  }

  public static Object put(URL url, String data, Map<String, String> headers) {
    return http(url, "PUT", data, headers);
  }

  public static Object delete(URL url, String data, Map<String, String> headers) {
    return http(url, "DELETE", data, headers);
  }

  private static Object http(URL url, String method, String data, Map<String, String> headers) {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    Authenticator.setDefault(new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username", "password".toCharArray());
      }
    });
    connection.setRequestMethod(method);

    for (String header : headers.keySet()) {
      connection.setRequestProperty(header, headers.get(header));
    }

    if (data != null) {
      connection.setRequestProperty("Content-Type", "application/json");
      connection.setDoOutput(true);
      OutputStream outputStream =connection.getOutputStream();
      outputStream.write(data.getBytes());
    }

    int responseCode = connection.getResponseCode();
    switch (responseCode) {
      case HttpURLConnection.HTTP_NO_CONTENT:
        // This happens when the server doesn't give back content, but all was ok.
        return (new HashMap());
      case HttpURLConnection.HTTP_OK:
        InputStream inputStream = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String response = reader.readLine();

        JsonSlurper parser = new JsonSlurper();
        Object jsonResponse = parser.parseText(response); // This can be either a List or a Map
        // Close the connection
        try { connection.close(); } catch (Exception e) { /* Already closed */ }
        return jsonResponse;
      default:
        println "response code: " + responseCode;
        println connection.getResponseMessage();
        println connection.getHeaderFields();
        // Close the connection
        try { connection.close(); } catch (Exception e) { /* Already closed */ }
        return null;
    }
  }
}

用法:

URL appointmentSearchURL = new URL("http://localhost:8080/rest/appointment/appointments/search/?fromDate=2016-11-21&branchId=3");
Object response = RESTclient.get(appointmentSearchURL, new HashMap<String, String>());
println response;

所有打印出来的内容:

response code: 400
Bad Request
[null:[HTTP/1.1 400 Bad Request], Server:[GlassFish Server Open Source Edition 3.1.2.2], Connection:[close], Set-Cookie:[rememberMe=deleteMe; Path=/; Max-Age=0; Expires=Tue, 22-Nov-2016 08:43:29 GMT, SSOcookie=2a86cf4b-a772-435a-b92e-f12845dc20a2; Path=/; HttpOnly], Content-Length:[1090], Date:[Wed, 23 Nov 2016 08:43:28 GMT], Content-Type:[text/html], X-Powered-By:[Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)]]
null

最佳答案

我找到了答案!因此,如果将来有其他人遇到同样的问题,我会将其留在这里:

缺少 Accept header ,我猜服务器端只接受 json 内容。我没有进一步研究为什么 WildFly 服务器不响应 400 错误请求,但我认为 WildFly 尝试猜测/推断传入的数据。

因此,通过添加以下内容解决了整个问题:

connection.setRequestProperty("Accept", "application/json");

关于java - GlassFish 3 - GET/POST/PUT/DELETE 上的 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760051/

相关文章:

java - Groovy 与 Java - 浮点精度的差异

java - 如何在受限沙箱中运行 java 代码(无网络、文件系统访问)

java - 为 tls 握手指定密码套件

rest - 将定制的聊天机器人与 Skype 集成

groovy - Geb 的一般问题(StaleElementReferenceException 和等待超时)

jenkins - 从Jenkinsfile写日志

java - 未知的框架尺寸

java - 字节到整数

java - Jersey REST 错误,找不到媒体类型 = application/json 的 MessageBodyWriter

json - 数据未从 Node.js 保存到 MongoDB 中