5

问题

我正在获取groovyx.net.http.HttpResponseException: Not Found并希望查看来自HTTPBuilder. 我将Groovy 2.1.9groovyConsole.

我试过的

所以我查看了这篇关于添加log4j.xmlgroovy.home/conf/. 我做到了,这是我的文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p  %c{1} - %m%n" />
        </layout>
    </appender>

    <category name="groovyx.net.http">
        <priority value="DEBUG" />
    </category>

    <!-- Use DEBUG to see basic request/response info;  
         Use TRACE to see headers for HttpURLClient. -->
    <category name="groovyx.net.http.HttpURLClient">
        <priority value="INFO" />
    </category>

    <category name="org.apache.http">
        <priority value="DEBUG" />
    </category>
    <category name="org.apache.http.headers">
        <priority value="DEBUG" />
    </category>
    <category name="org.apache.http.wire">
        <priority value="DEBUG" />
    </category>

    <root>
        <priority value="INFO" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

这是我在控制台中运行的脚本:

import groovyx.net.http.*
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager
import javax.net.ssl.SSLContext
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManager
import java.security.SecureRandom
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.scheme.SchemeRegistry

import groovy.util.logging.*

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6')
@Grab( 'log4j:log4j:1.2.16' )
@Log4j
class WebserviceTest {
  static void main (String[] args) {

    def http = new HTTPBuilder('https://localhost:8443/project/service/')
    log.debug "http is instanceof ${http.getClass()}" //this is printed

    //=== SSL UNSECURE CERTIFICATE ===
   def sslContext = SSLContext.getInstance("SSL")              
   sslContext.init(null, [ new X509TrustManager() {
     public X509Certificate[] getAcceptedIssuers() {null}
     public void checkClientTrusted(X509Certificate[] certs, String authType) { }
     public void checkServerTrusted(X509Certificate[] certs, String authType) { }
   } ] as TrustManager[], new SecureRandom())
   def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
   def httpsScheme = new Scheme("https", sf, 4483)
   http.client.connectionManager.schemeRegistry.register( httpsScheme )
   //================================

    //the next line throws the exeption...
    http.post(path: '/method', contentType: ContentType.JSON, query: [param: '1000']) { resp, reader ->
        println "resp is instanceof ${resp.getClass()}"
        println "and reader is instanceof ${reder.getClass()}"

        println "response status: ${resp.statusLine}"
        println 'Headers: -----------'
        resp.headers.each { h ->
          println " ${h.name} : ${h.value}"
        }
        println 'Response data: -----'
        System.out << reader
        println '\n--------------------'

    }
  } 
}

编辑:我的 HttpResponseException 已解决,我/在请求中有一个不必要的,但仍然没有出现生成器日志。

4

2 回答 2

2

HTTPBuilder使用 commons-logging,因此您必须将 commons-logging 的输出连接到 log4j。不幸的是 log4j 1.2 不支持这个开箱即用。因此,我简化了您的示例并切换到SLF4J,这是一个“Java 的简单日志记录外观”。在幕后,以下配置仍然使用 log4j,所以你仍然需要你的log4j.xmlin place ( groovy.home/conf/)。有关详细说明,请参阅桥接旧版 API

@Grapes([
    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6'),
    // This brings in slf4j, log4j12 (as dependancies) and the bridge to log4j
    @Grab(group='org.slf4j', module='slf4j-log4j12', version='1.7.7'),
    // This brings in the bridge to commons-logging
    @Grab(group='org.slf4j', module='jcl-over-slf4j', version='1.7.7')
])

import org.slf4j.LoggerFactory
import groovyx.net.http.*

// get a logger for the script
def log = LoggerFactory.getLogger('script')

def http = new HTTPBuilder('http://www.google.com')
log.info "http is instanceof ${http.getClass()}" //this is printed

http.get( path : '/search', contentType : ContentType.TEXT, query : [q:'Groovy'] ) { resp, reader ->
    log.debug "response status: ${resp.statusLine}"
    println 'Done'
}
于 2014-05-29T12:31:05.293 回答
0

试试这个 导入这个

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger

并设置

Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)
rootLogger.setLevel(mLevel)

您可以在调用 HTTP 构建器之前设置它

于 2017-07-17T10:57:35.110 回答