簡體   English   中英

GlassFish 3 - 400 GET / POST / PUT / DELETE請求錯誤

[英]GlassFish 3 - 400 Bad Request on GET/POST/PUT/DELETE

在我的腳本中,我創建了一個小而簡單的REST客戶端。 腳本本身就是一個原型,因此代碼不是“生產有價值” - 所以忽略懶惰的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標頭,我猜服務器端只接受json內容。 我還沒有進一步研究為什么WildFly服務器沒有響應400錯誤請求,但我想WildFly會嘗試猜測/推斷傳入的數據。

所以通過添加以下內容解決了整個問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM