如何传递多组http参数来访问Web服务

时间:2015-03-22 20:06:14

标签: java rest nessus

当我正在使用Nessus扫描仪时,我必须传递参数来创建扫描。请求的正文应该是:

    {
      "uuid": {template_uuid},
      "settings": {
        "name": {string},
        "description": {string},
        "emails": {string},
        "launch": {string},
        "folder_id": {integer},
        "policy_id": {integer},
        "scanner_id": {integer},
        "text_targets": {string}
      }
    }

目前我正尝试通过以下代码传递这些参数:

public static void createScan(){
    String url = SERVER_URL+"/scans";
    String[] paramName = {"uuid", "settings.name","settings.policy_id","settings.text_targets"};
    String[] paramVal = {"xxxx", "xxxx", "xxxx","xx.xx.xxx.xxx"};
        try {
            String token = login();
            httpPost(url, paramName, paramVal, token);
        } catch (Exception e) {
            e.printStackTrace();
        }
}
public static String httpPost(String urlStr, String[] paramName, String[] paramVal, String token) throws Exception {
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setConnectTimeout(500000);
        conn.setReadTimeout(500000);
        conn.setRequestProperty("X-Cookie:", "token=" + token + ";");


        if (paramName != null && paramVal != null) {
            OutputStream out = conn.getOutputStream();
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            for (int i = 0; i < paramName.length; i++) {
                writer.write(paramName[i]);
                writer.write("=");
                writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
                writer.write("&");
            }
            writer.close();
            out.close();
        }

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
    conn.disconnect();
    return sb.toString();
}

目前通过运行上面的代码我得到了:

Response code: 403
java.io.IOException: Unauthorized

请帮我成功传递这些参数,以便在Nessus中创建扫描

1 个答案:

答案 0 :(得分:0)

我无法真正帮助您解决这个问题,但您应该考虑使用jackson或其他一些xml / json解析器,因为您似乎需要使用JSON发送数据。更容易传递一个对象,Jackson解析器会将其转换为JSON。

有关详情:http://jackson.codehaus.org/

另外考虑使用apache httpclient,因为它包含在android中。方式不那么凌乱,更容易维护。