给出错误的Java代码:语法错误或令牌" 1",<预期

时间:2014-12-21 16:41:13

标签: java android http

我正在尝试向Hackerrank API发出HTTP POST请求,但代码未编译并提供错误语法错误或令牌" 1",<预期。其中一个POST参数是' testcase'这需要是一个字符串,但这是eclipse给出错误的地方。如果我不放" "在1左右它工作正常,但现在Hackerrank API提供响应代码:400因为testcase需要是字符串。我无法弄清楚如何解决这个问题。有人可以指导我。

提前致谢。这是代码:

package com.us.ABC;

import java.io.BufferedReader;  
import java.io.DataOutputStream;  
import java.io.InputStreamReader;  
import java.net.HttpURLConnection;  
import java.net.URL;

public class HttpURLConnectionExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpURLConnectionExample http = new HttpURLConnectionExample();

        System.out.println("\nTesting 2 - Send Http POST request");
        http.sendPost();

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "http://api.hackerrank.com/checker/submission.json";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add request header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "source=print 1&lang=5&testcases=["1"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";

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

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

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

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

}

1 个答案:

答案 0 :(得分:5)

您需要转义字符串文字中的双引号:

String urlParameters = "source=print 1&lang=5&testcases=[\"1\"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";