如何使用java.net制作Post Json rpc

时间:2018-07-21 15:37:42

标签: java json api https rpc

我必须对要在网址中包含变量的json-rpc api进行https发布。在这种情况下:

https://mese.webuntis.com/WebUntis/jsonrpc.do?school=GS+T%C3%BCbingen

(这是一台公共服务器,不是我自己的,因此请自行破解)。 服务器仅接受https并拒绝不使用学校名称(GS + T%C3%BCbingen)的任何事情:

{"jsonrpc":"2.0","id":"error","error":{"message":"invalid schoolname","code":-8500}}

另外想使用默认的java.net库。

我通过以下回复接受学校名称:

{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream@396fcdd0; line: 1, column: 0]"}}

现在我必须将Json数据添加到我的帖子中,但是当我尝试添加时。它使我得到了一个不俗的学校名称响应。

我尝试了一些尝试,但是我对Java不满意,这是我当前的代码。

public class Main {

private final String USER_AGENT = "Mozilla/5.0";


public static void main(String[] args) {

    Main http = new Main();
    String output;
    String data;
    String dataEncoded;
    String schoolName;
    String url;

    data = "{\"id\":\"ID\",\"method\":\"authenticate\",\"params\":{\"user\":\"ANDROID\",\"password\":\"PASSWORD\", \"client\":\"CLIENT\"},\"jsonrpc\":\"2.0\"}";
    dataEncoded = "%7B%22id%22%3A%22ID%22%2C%22method%22%3A%22authenticate%22%2C%22params%22%3A%7B%22user%22%3A%22ANDROID%22%2C%20%20%22password%22%3A%22PASSWORD%22%2C%20%22client%22%3A%22CLIENT%22%7D%2C%22jsonrpc%22%3A%222.0%22%7D";
    schoolName = "GS+T%C3%BCbingen";// gs tübingen encoded for http
    url = "https://mese.webuntis.com/WebUntis/jsonrpc.do";

    System.out.println("\nTrying Https Post to: " + url + " with SchoolName: " + schoolName + " with data: " + data);
    output = http.sendPost(url,schoolName,data);
    System.out.println("---Response Start---\n" + output + "\n---Response End---");


}

private String sendPost(String url,String schoolName,String data) {
    try {
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    //con.setRequestProperty("Content-Type", "application/json-rpc");
    //con.setRequestProperty("", data);

    String urlParameters = "school=" + schoolName ;//+ "&" + data;

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();


    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    return response.toString();
    }
    catch(IOException e){
        return "sensPost() failed: "+ e.getMessage();
    }

}

我发现我必须将json数据插入到html主体中,但我不知道该如何处理以及该数据是否还必须进行ascii-%编码。(对我的混乱代码表示抱歉,但这仅用于测试才能正确实施。)

-Sammy

0 个答案:

没有答案