Java相当于AJAX代码

时间:2016-07-16 18:03:46

标签: javascript android jquery

我想在我的应用中使用API​​。在它的指南中,它显示我建立这样的连接 -

Subject

我正在为Android调用此调用。我已经像这样使用了$.ajax( { type: "POST", url: baseUrl + "query/", contentType: "application/json; charset=utf-8", dataType: "json", headers: { "Authorization": "Bearer " + accessToken, "ocp-apim-subscription-key": subscriptionKey }, data: JSON.stringify({q: text, lang: "en"}), //text is a String variable success: function(data) { prepareResponse(data); }, error: function() { respond(messageInternalError); } }); -

HttpURLConnection

现在我可以使用setRequestProperty()来设置Header和contentType部分。但我不知道如何设置URL url = new URL(baseUrl + "query/"); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); data部分。

请帮帮我。

1 个答案:

答案 0 :(得分:0)

    URL url = new URL(baseUrl + "query/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");

    // Set the headers
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestProperty("Authorization", "Bearer " + accessToken);
    conn.setRequestProperty("ocp-apim-subscription-key", subscriptionKey);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Create a JSON object to hold the data
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("q", text);
    jsonObj.put("lang", "eng");

    // Write JSON object
    OutputStream os = conn.getOutputStream();
    os.write(jsonObj.toString().getBytes("UTF-8"));
    os.flush();
    os.close();

    int responseCode = conn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        // success, get result from server
        BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } else {
        // error
        System.out.println(conn.getResponseMessage());  
    }