NodeJS 通过jenkins-api调用Jenkins updage_job中文编码问题

最近项目需要,基于Jenkins+Fastlane 搭建一套CI系。

通过NodeJS调用Jenkins API。

使用jenkins-api 这个包封装的接口,发现在执行Update_Job方法时,如果传入的参数中含有中文,则更新之后,此Job对应的配置信息(即config.xml 中)所有关于中文的地方都会乱码。

 

但是对比通过Java 的一个库:

com.offbytwo.jenkins:jenkins-client:0.3.8

执行更新时,Job配置正常,无奈抓包对比两此的请求,发现通过node 的 jenkins-api这个库,在请求的header里 Content-Type字段少了一个 charset=UTF-8',测试对比,直接通过原始的HTTP库调用,增加这个字段之后,更新中文正常。

 

 

关于NodeJS  和 Intellj 抓包

 

开启Charles,默认是无法抓到NodeJS 和 在Intellj 中执行的Java代码的包的,需要在代码中增加代理设置:

 

NodeJS:

推荐使用urllib这个库,通过enableProxy方式将请求代理到Charles上

urllib.request('http://host:port/job/job_name/config.xml/api/json', {
        enableProxy: true,
        proxy: 'http://localhost:8888',
        method: 'POST',
        headers: {
            'Authorization': 'basic ' + new Buffer(jenkinsUser + ':' + jenkinsPassword).toString('base64'),
            'Content-Type': 'text/xml; charset=UTF-8',
        },
        content: configData
    },function(err,data,res){
      console.log(JSON.stringify(data));
    });

 

IntellJ:

推荐使用HttpPost这个class来做代理(gradle坐标:org.apache.httpcomponents:httpclient:4.3.6):

public static void updateJob() throws URISyntaxException, IOException {
        HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .build();

        HttpPost request = new HttpPost(UrlUtils.toJsonApiUri(new URI("http://jenkinsHost:jenkinsPort"), "/", "/job/job_name/config.xml"));

        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        HttpResponseValidator httpResponseValidator = new HttpResponseValidator();

        request.setEntity(new StringEntity(xml, ContentType.create("text/xml", "utf-8")));
        request.setHeader("Authorization","basic anVtbzp0YW9iYW8xMjM0");
        HttpResponse response = client.execute(request);
        //jenkinsVersion = ResponseUtils.getJenkinsVersion(response);
        try {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
        } finally {
            EntityUtils.consume(response.getEntity());
            request.releaseConnection();

        }
    }

 

你可能感兴趣的:(NodeJS)