【问题标题】:Request to server API using Java and JSON使用 Java 和 JSON 向服务器 API 请求
【发布时间】:2013-10-21 18:54:23
【问题描述】:

我有几种方法的服务器 API 文档。问题是我从未使用过 API 来处理服务器。我该怎么做才能更轻松?

部分 API 文档:

方法“登录”:

发布http://api.example.com/login-ajax

参数:

  • 电子邮件

  • 密码

回应:

{
    "success":true,
    "currentUser":222,
    "userData":{
        "displayName":"User",
        "displayAvatarId":"asjhdsasduh",
        "email":"qwerty@gmail.com",
        "isEmailConfirmed":"0",
        "sex":"m"
    }
}

响应是 JSON 对象,但我不知道如何发送请求以获取此响应。

请帮帮我。

升级

我尝试使用 Jsoup:

Connection.Response res = Jsoup.connect("http://api.example.com/login-ajax")
                .data("email", "mail@gmail.com", "password", "pass")
                .method(Connection.Method.POST)
                .header("Accept", "application/json")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("X-App-Api", "1.0")
                .header("X-App", "iOS")
                .ignoreContentType(true)
                .execute();
        Document document = Jsoup.parse(res.parse().outerHtml());
        System.out.println(document.text());

回复是:

{"success":false,"exception":"Exception_User","message":"\u041c\u044b \u043d\u0435 \u043d\u0430\u0448\u043b\u0438 \u0432 \u0431\u0430\u0437\u0435 \u0442\u0430\u043a\u043e\u0435 \u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u0435 \u044d\u043b. \u043f\u043e\u0447\u0442\u044b \u0438 \u043f\u0430\u0440\u043e\u043b\u044f. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437."}

升级 2

我也试过用这个:

System.out.println(getJSON("http://api.example.com/login-ajax"));

public static String getJSON(String url) {
        try {
            URL u = new URL(url);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("POST");
            c.setRequestProperty("email", "mail@gmail.com");
            c.setRequestProperty("password", "pass");
            c.setRequestProperty("Accept", "application/json");
            c.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            c.setRequestProperty("X-App-Api", "1.0");
            c.setRequestProperty("X-App", "iOS");
            c.setUseCaches(false);
            c.setAllowUserInteraction(false);
            c.setConnectTimeout(1000);
            c.setReadTimeout(1000);
            c.connect();
            int status = c.getResponseCode();

            switch (status) {
                case 200:
                    System.out.println("200");
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();
                    return sb.toString();
                case 201:
                    System.out.println("201");
                    br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();
                    return sb.toString();
            }

        } catch (MalformedURLException ex) {
            System.out.println("MalformedURLException");
        } catch (IOException ex) {
            System.out.println("IOException");
        }
        return null;
    }

响应是:

{"success":false,"exception":"Exception_Validation","message":"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u044b\u0439 e-mail","errors":{"email":["\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 e-mail."],"password":["\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043f\u0430\u0440\u043e\u043b\u044c"]}}

【问题讨论】:

  • 不知道什么是请求参数?以 URL 结尾的表单参数?
  • 我知道它是什么,但我不知道如何使用它们。
  • 阅读 HTTP,然后找到并使用 Java HTTP 客户端。
  • 我尝试使用 Jsoup 发出 post 请求,但我得到了不好的响应。
  • 向我们展示您尝试的所有细节。

标签: java json api request response


【解决方案1】:

由于到目前为止我还没有使用过 Jsoup,我无法提供有关如何使用它的详细信息,但我必须使用 Restlet,因此创建了我自己的 JSON 消息(通过 org.json.JSONObject 或通过普通细绳)。使用 Restlet 的后期示例如下所示:

try
{
    // create a Restlet client
    ClientResource cr = new ClienResource("http://api.example.com/login-ajax");
    // create the JSON message
    JSONObject message = new JSONObject();
    message.put("email", "mail@gmail.com");
    message.put("password", "pass");
    // use HTTP POST method to send the JSON message
    cr.post(message, MediaType.APPLICATION_JSON);

    // receive the answer - error checks omitted!
    Response response = cr.getResponse();
    JsonRepresentation jsonRep = new JsonRepresentation(response.getEntity());

    // process the JSON response
    JSONObject json = jsonRep.getJsonObject();
    System.out.println("success: "+json.get("success"));
    System.out.println("current user: "+json.get("currentUser"));

    // extract the user data
    JSONObject userData = (JSONObject)json.get("userData");
    System.out.println("display name: "+userData.get("displayName"));
    System.out.println("display avatar Id: "+userData.get("displayAvatarId"));
    System.out.println("email: "+userData.get("email"));
    System.out.println("is email confirmed: "+userData.get("isEmailConfirmed"));
    System.out.println("sex: "+userData.get("sex"));
}
catch (ResourceException | JSONException ex)
{
    ex.printStackTrace();
}

HTH

【讨论】:

  • 我加载了 Restlet,但如何将 Restlet 导入我的项目?
【解决方案2】:

考虑使用Apache HTTP Client 来创建到您的HTTP 服务器的连接。 它是一个用于处理 HTTP 请求的通用库。有很多资源可以说明HTTP客户端的使用,Here is an example

我承认,我从未使用过 JSoup,所以我无法对您的示例发表评论。

希望这会有所帮助, 标记

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 2015-02-15
    • 1970-01-01
    相关资源
    最近更新 更多