簡體   English   中英

使用json參數訪問Java中的REST API

[英]Access REST API in Java with json parameters

我不知道自己在做什么錯,但是我無法使用Java中帶有Json參數的POST方法訪問REST API

每次運行程序時,都會收到Java.net.SocketException - Connection Reset

我試圖從PHP訪問API,並且它起作用了。

代碼: https//github.com/BobTheProgrammer/Question/blob/master/POST

試試這個

    public static void HttpPost() {
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "https://api.website.net/auth/token");
        StringEntity input = new StringEntity("{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}");
        post.setEntity(input);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

第55行的源代碼中的JSON語法存在問題,您錯過了用戶對象后的逗號。

替換此行

String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"}\"method\":\"user\",\"website\":\"http://website.net/\"}}";

與此(在方法之前,在用戶對象之后添加逗號)

String urlParameters = "{\"auth\":{\"user\":{\"id\":\"bla\",\"password\":\"bla\"},\"method\":\"user\",\"website\":\"http://website.net/\"}}";

暫無
暫無

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

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