如何在 Java 中处理 Github Webhook?

How to handle Github Webhook in Java?

简单的问题。

在 Github 上注册了有效负载 URL:使用 ngrok.com(ngrok) link like explained in Github documentation for Webhooks: Creating Webhooks

ngrok definition: “I want to securely expose a local web server to the internet and capture all traffic for detailed inspection and replay.”


当我在正确的有效负载 URL 上发送带有来自 github 的有效负载的 POST 请求时,响应代码是 200,我该如何处理 request/response 并在 java 中获取负载 (JSON)?用 servlet 还是?
我不知道从哪里开始。试图搜索但没有找到 Java :(

  1. 如果我输入 ngrok.com/something,Eclipse 控制台抛出:
    [WARN] 404 - POST /pas (127.0.0.1) 1368 bytes Request headers Host: ....ngrok.com X-Real-IP: 192.... X-Forwarded-Proto: http Connection: close Content-Length: 5759 Accept: */* User-Agent: GitHub-Hookshot/e9dfd89 X-GitHub-Event: ping X-GitHub-Delivery: c5493000-b67e-11e4-8199-8b09d3d66948 Content-Type: application/json X-Hub-Signature: sha1=b2947ce6a6de23f4274831523bae375d64e20021 Response headers Connection: close Content-Type: text/html;charset=ISO-8859-1 Cache-Control: must-revalidate,no-cache,no-store Content-Length: 1368
  2. 如果我输入好 URL,状态为 200。响应 Github Webhooks / Manage webhook:
    Accept-Ranges: bytes Connection: keep-alive Content-Length: 1521 Content-Type: text/html Date: Tue, 17 Feb 2015 10:17:46 GMT Last-Modified: Thu, 12 Feb 2015 09:06:18 GMT Server: nginx/1.6.2

所以问题其实是"How to handle that payload?"

Sinatra 代码如下所示:
require "sinatra" require "json" post "/payload" do push = JSON.parse(request.body.read) puts "I got some JSON: #{push.inspect}" end
对此很陌生,抱歉,这是个愚蠢的问题。

已解决,我使用 HttpServlet doPost 方法来获取请求,然后从请求中获取 getReader() 并读取行,这样我就可以创建 JSONObject。我的 servlet 在 page/Payload 上,Webhook 在 http://server.com/page/Payload

public class Payload extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    StringBuilder builder = new StringBuilder();
    String aux = "";

    while ((aux = req.getReader().readLine()) != null) {
        builder.append(aux);
    }

    String text = builder.toString();
    try {
        JSONObject json = new JSONObject(text);
        String teams_url = json.getJSONObject("repository").getString("teams_url");
        System.out.println("Teams URL:: "+teams_url);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }}

你可以利用gitlab4j-api library. For example usage, have a look at simple review project, exactly here: https://github.com/gitlab4j/simple-cr/blob/master/src/main/java/org/gitlab4j/simplecr/service/GitLabWebHookService.java