如何将params和Cookie添加到http post java请求?

时间:2012-01-11 13:13:07

标签: java http

我正在尝试调用一个Web服务方法,该方法需要2个输入参数,并且还需要cookie进行身份验证。

        PostMethod method = new PostMethod("webservice EP URL");
        NameValuePair code = new NameValuePair("Code", "");
        NameValuePair revision = new NameValuePair("Rev", "Latest");

        NameValuePair targetUri = new NameValuePair("TARGET", "GetObject");
        method.setRequestBody(new NameValuePair[] { code, revision,targetUri});
        int statusNew = client.executeMethod(method);

我不知道如何实现它。以上代码是我目前正在做的事情。

2 个答案:

答案 0 :(得分:0)

很可能你正在处理RESTful Web服务(只是我的猜测,因为你将参数作为http形式参数传递)。以下是传递cookie的方法

method.setRequestHeader("Cookie", "special-cookie=value");

此处只需将"special-cookie=value"更改为您尝试传递的特定Cookie。

编辑:向SOAP请求添加Cookie

最快的方法如下

(假设您使用的call对象是org.apache.axis.client.Call的实例)

call.setProperty(
        org.apache.axis.client.Call.SESSION_MAINTAIN_PROPERTY, 
        new Boolean(true));
    call.setProperty(
        org.apache.axis.transport.http.HTTPConstants.HEADER_COOKIE2, 
        "\r\nCookieName=" + "CookieValue");

请在this链接上查看“使用SOAPAction HTTP标头”主题。

答案 1 :(得分:-1)

使用SOAP Handler,我们可以在请求中传递标题,它将完成这项工作。

GetObject_Service_Impl impl = new GetObject_Service_Impl();
        // Get Iterator for all service ports
        Iterator iter = impl.getPorts();

        // Now create a new List of HandlerInfo objects - only one really.
        // Our client handler
        List handlerChain = new ArrayList();
        handlerChain.add(new HandlerInfo(SoapHandler.class, null, null));

        // Get Handler Registry
        HandlerRegistry registry = impl.getHandlerRegistry();
        // Register each port with the handler
        while (iter.hasNext())
            registry.setHandlerChain((QName) iter.next(), handlerChain);

并写一个新类说SoapHandler.java如下

公共类SoapHandler扩展了GenericHandler {

HandlerInfo hi;

public void init(HandlerInfo info) {
    hi = info;
}

public QName[] getHeaders() {
    return hi.getHeaders();
}

public boolean handleResponse(MessageContext context) {

    return true;
}

/**
 * This method is use to add custom headers to existing SAOP request
 */
public boolean handleRequest(MessageContext context) {
    System.out.println("response");

    try {
        SOAPMessageContext smc = (SOAPMessageContext) context;
        SOAPMessage message = smc.getMessage();
        MimeHeaders hd = message.getMimeHeaders();
        hd.addHeader("Authorization", "Basic some credentials");

    } catch (Exception e) {
        throw new JAXRPCException(e);
    }
    return true;
}

}

这就是.....它准备好了。