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

var*_*nkr 2 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());

    }

}
Run Code Online (Sandbox Code Playgroud)

man*_*uti 5

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

String urlParameters = "source=print 1&lang=5&testcases=[\"1\"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";
Run Code Online (Sandbox Code Playgroud)