获得400响应httpurlconnection发送帖子请求

时间:2016-03-15 15:03:17

标签: java json httprequest httpurlconnection http-status-code-400

尝试将python代码转换为httpsost请求的java代码,但总是得到400响应。在我的计算机上使用一些本地Web服务尝试相同的代码,没有任何问题。请参阅python代码:

post_data = {'monitoredObjects':'VZLab-IViewG10-2','monitoredObjectType':'Probe'}

print(post_data)

postfields = urlencode(post_data)


response = BytesIO()

b = pycurl.Curl()

b.setopt(b.URL, base+"capture")

b.setopt(b.HTTPHEADER, ['username:'+username,'securitytoken:'+securitytoken])

b.setopt(b.SSL_VERIFYPEER, 0)

b.setopt(a.SSL_VERIFYHOST, 0)

b.setopt(b.WRITEDATA, response)

b.setopt(b.POST, 1)

b.setopt(b.POSTFIELDS, postfields)

b.perform()

b.close()

我的java代码:

public void method(){
    String securityToken = "12134";
    HashMap<String, String> header = new HashMap<String, String>();

    header.put("username", username);
    header.put("password", password);
    header.put("securitytoken", securityToken);

    String api = "capture";

    JsonObject parameters = new JsonObject();

    parameters.addProperty("monitoredObjects", System.getProperty("monitoredObjects"));

    parameters.addProperty("monitoredObjectType", System.getProperty("monitoredObjectType"));
    String captureResult = executePost(baseUrl, api, header, parameters.toString(), "POST");

    String captureid = Xml.getXPathValue(result, "//startCapture/isa:captureId/text()");
}

public static String executePost(String baseUrl, String api, HashMap header, String urlParameters, String httpMethod) {
    HttpURLConnection connection = null;
    try {
        // Create connection
        URL url = new URL(baseUrl + api);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Language", "en-US");

        connection.setRequestProperty("username", (String) header.get("username"));
        connection.setRequestProperty("securitytoken", (String) header.get("securitytoken"));

        /*
         * String userPassword = username + ":" + password; String encoding = new
         * sun.misc.BASE64Encoder().encode(userPassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " +
         * encoding);
         */

        // connection.setRequestProperty("Accept-Encoding", "gzip");

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        // Send request
        if (urlParameters != null) {
            String encodedString = URLEncoder.encode(urlParameters);
            OutputStream wr = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
            writer.write(encodedString);
            writer.flush();
            writer.close();
            wr.close();

            // wr.write(urlParameters.getBytes("UTF-8"));
            // wr.close();
        }
        int responseCode = connection.getResponseCode();
        logger.info("\nSending 'POST' request to URL : " + url);
        logger.info("Post headers : " + header);
        logger.info("Post parameters : " + urlParameters);
        logger.info("Response Code : " + responseCode);
        // Get Response
        if (responseCode == 200) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();

            logger.info("*** BEGIN ***");
            logger.info(response.toString());
            logger.info("*** END ***");
            return response.toString();
        }
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage());
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我可以看到你在python上使用了一个Json对象作为你的请求参数,并使用urlencode在格式正确的url参数中转换了这个Json对象。 urlencode要求Json Object作为参数,但这对于Java来说是不同的。

URLEncoder.encode方法需要String对象作为参数,然后您不需要在Java代码上创建Json对象,您应该这样做:

...
String parameters = "monitoredObjects=VZLab-IViewG10-2&monitoredObjectType=Probe";
URLEncoder.encode(parameters);
...

现在,我知道你将Json对象转换为String对象(parameters.toString()),但它只做了类似的事情:

"{monitoredObjects:VZLab-IViewG10-2,monitoredObjectType:Probe}"

因此,它不是一个格式正确的网址,因此您可以获得400 HTTP响应。

我分享了URLEncoder类的文档。

https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html#encode%28java.lang.String%29

我希望这些信息可以帮到你。

祝你好运。