为grpc java客户端请求填充标头

时间:2017-03-14 16:41:59

标签: java grpc-java

我目前没有使用CallCredentials和GRPC-Java。我需要传入标题中的多个字段以进行某些调用。我已经填充了下面给出的标头,并添加了一个拦截器,在使用异步存根/通道时调用它。

填充标题

public Metadata generateHeader() {
    Metadata.Key<String> jwtKey = Metadata.Key.of("jwt", Metadata.ASCII_STRING_MARSHALLER);
    headers.put(jwtKey, jwt);
    Metadata.Key<String> testKey = Metadata.Key.of("testID", Metadata.ASCII_STRING_MARSHALLER);
    headers.put(testKey, testID);
    return headers;
} 

我正在访问headers字段作为传递给客户端拦截器的实例变量。我可以看到标题包含预期的值,直到它进入启动调用,此时它变为空(我显然没有看到服务器端填充的标题)。任何想法来解决这个问题(或者我应该使用CallCredentials)。 GRPC-Java的文档需要大量工作。

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> method,
        CallOptions callOptions,
        Channel next) {
    log.info("HEADER INTERCEPTOR{}", headers.get(Metadata.Key.of("jwt", Metadata.ASCII_STRING_MARSHALLER)));
    ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
    return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) {
        @Override
        public void start(ClientCall.Listener<RespT> responseListener, Metadata headers) {
            log.info("HEADER START {}", headers.keys());
            super.start(responseListener, headers);
        }
    };
}  

1 个答案:

答案 0 :(得分:0)

我必须通过方法调用访问标题,之后我才能获得标题键/值。

   public Metadata getHeaders() {
        return headers;
}

&安培;

func copyFolderFromThisAppMainToUserDocument(folderName: String) -> Bool {

    let fileMgr = FileManager.default
    let userDocumentURL = fileMgr.urls(for: .documentDirectory, in: .userDomainMask).first!
    let urlForCopy = userDocumentURL.appendingPathComponent(folderName, isDirectory: true)
    if let bundleURL = Bundle.main.url(forResource: folderName, withExtension: "") {
        // if exist we will copy it
        do {
            try fileMgr.copyItem(at: bundleURL, to: urlForCopy)
            return true
        } catch let error as NSError { // Handle the error
            print("\(folderName) copy failed! Error:\(error.localizedDescription)")
            return false
        }
    } else {
        print("\(folderName) not exist in bundle folder")
        return false
    }
}