如何在Web服务引用上设置HTTP请求标头?

时间:2014-05-30 21:41:13

标签: web-services http-headers

这是问题......

我有一个适用于JAVA代码的网络服务......

package com.mypackage.myproject;

 public class ExecuteGetOrder {


public static void main(String [ ] args)
{
     try {



        runGetOrder();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}




public static void runGetOrder() throws Exception
 {

        GetOrderDataInterface data = new GetOrderDataInterfaceProxy().getGetOrderDataInterface();
        ((org.apache.axis.client.Stub)data)._setProperty(org.apache.axis.client.Call.USERNAME_PROPERTY, "ent=,user=UserName");
        ((org.apache.axis.client.Stub)data)._setProperty(org.apache.axis.client.Call.PASSWORD_PROPERTY, "password");
        String RtrnDataXML = data.OrderInfo("OrderNumber");
        System.out.println(RtrnDataXML);




}



}

Raw请求看起来像这样......

POST http://win-bpqhaq6l0jt:8008/oms/services/GetOrderData HTTP/1.0
Content-Type: text/xml; charset=utf-8
Accept: application/soap+xml, application/dime, multipart/related, text/*
User-Agent: Axis/1.4
Host: win-bpqhaq6l0jt:8008
Cache-Control: no-cache
Pragma: no-cache
SOAPAction: ""
Content-Length: 366
Authorization: Basic ZW50PSx1c2VyPUEyTENNQWRtaW46cGFzc3dvcmQ=

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ammoOrderInfo xmlns="http://a2lcm.rhinotechnology.com/"><order xmlns="">OrderNumber</order></OrderInfo></soapenv:Body></soapenv:Envelope>

现在我想在VB.NET windows应用程序中做同样的事情。首先我添加了服务引用,但是当我尝试使用使用此代码生成的类时......

    Dim OrderService As getOrderData.GetOrderDataInterfaceClient = New getOrderData.OrderDataInterfaceClient()
    Dim returnedXMl = OrderService.OrderInfo("Order")

我回来了......

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
WWW-Authenticate: Basic host=10.20.100.7
Content-Type: text/html;charset=utf-8
Content-Length: 948
Date: Fri, 30 May 2014 21:25:05 GMT

<html><head><title>JBossWeb/2.0.1.GA - Error report</title><style><!--H1 {font- family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-  family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p>  <b>description</b> <u>This request requires HTTP authentication ().</u></p><HR size="1" noshade="noshade"><h3>JBossWeb/2.0.1.GA</h3></body></html>

所以问题是如何设置HTTP授权:在使用...

进行请求时
Dim OrderService As getOrderData.GetOrderDataInterfaceClient = New GetOrderData.OrderDataInterfaceClient()
Dim returnedXMl = OrderService.OrderInfo("Order")

1 个答案:

答案 0 :(得分:0)

所有尝试使用JBoss Web服务进行Basic身份验证的解决方案......

1)添加以下类(vb中的代码)

Imports System.ServiceModel.Dispatcher

Imports System.ServiceModel.Channels

Imports System.ServiceModel.Description

Imports System.ServiceModel.Configuration

Imports System.Configuration

Public Class HttpUserAgentMessageInspector
Implements IClientMessageInspector

Private Const USER_AGENT_HTTP_HEADER As String = "Authorization"

Private m_userAgent As String

Public Sub New(ByVal userAgent As String)
    MyBase.New()
    Me.m_userAgent = userAgent
End Sub

Public Sub AfterReceiveReply(ByRef reply As System.ServiceModel.Channels.Message, ByVal correlationState As Object) Implements IClientMessageInspector.AfterReceiveReply

End Sub

Public Function BeforeSendRequest(ByRef request As System.ServiceModel.Channels.Message, ByVal channel As System.ServiceModel.IClientChannel) As Object Implements IClientMessageInspector.BeforeSendRequest
    Dim httpRequestMessage As HttpRequestMessageProperty
    Dim httpRequestMessageObject As Object
    If request.Properties.TryGetValue(HttpRequestMessageProperty.Name, httpRequestMessageObject) Then
        httpRequestMessage = CType(httpRequestMessageObject, HttpRequestMessageProperty)
        If String.IsNullOrEmpty(httpRequestMessage.Headers(USER_AGENT_HTTP_HEADER)) Then
            httpRequestMessage.Headers(USER_AGENT_HTTP_HEADER) = Me.m_userAgent
        End If
    Else
        httpRequestMessage = New HttpRequestMessageProperty
        httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, Me.m_userAgent)
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage)
    End If
    Return Nothing
End Function
End Class
Public Class HttpUserAgentEndpointBehavior
Implements IEndpointBehavior

Private m_userAgent As String

Public Sub New(ByVal userAgent As String)
    MyBase.New()
    Dim headerBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(userAgent)
    Dim headerValue As String = ("Basic " + Convert.ToBase64String(headerBytes))
    Me.m_userAgent = headerValue
End Sub
#Region "IEndpointBehavior Members"

Public Sub AddBindingParameters(ByVal endpoint As ServiceEndpoint, ByVal bindingParameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IEndpointBehavior.AddBindingParameters

End Sub

Public Sub ApplyClientBehavior(ByVal endpoint As ServiceEndpoint, ByVal clientRuntime As System.ServiceModel.Dispatcher.ClientRuntime) Implements IEndpointBehavior.ApplyClientBehavior
    Dim inspector As HttpUserAgentMessageInspector = New HttpUserAgentMessageInspector(Me.m_userAgent)
    clientRuntime.MessageInspectors.Add(inspector)
End Sub

Public Sub ApplyDispatchBehavior(ByVal endpoint As ServiceEndpoint, ByVal endpointDispatcher As System.ServiceModel.Dispatcher.EndpointDispatcher) Implements IEndpointBehavior.ApplyDispatchBehavior

End Sub

Public Sub Validate(ByVal endpoint As ServiceEndpoint) Implements IEndpointBehavior.Validate

End Sub
#End Region
End Class
Public Class HttpUserAgentBehaviorExtensionElement
Inherits BehaviorExtensionElement

Public Overrides ReadOnly Property BehaviorType As Type
    Get
        Return GetType(HttpUserAgentEndpointBehavior)
    End Get
End Property

Protected Overrides Function CreateBehavior() As Object
    Return New HttpUserAgentEndpointBehavior(UserAgent)
End Function

<ConfigurationProperty("userAgent", IsRequired:=True)> _
Public Property UserAgent As String
    Get
        Return CType(Me("userAgent"), String)
    End Get
    Set(value As String)
        Me("userAgent") = value
    End Set
End Property
End Class   

2)将以下XML代码添加到system.serviceModel标记之间的app.config中。

  <behaviors>
         <endpointBehaviors>
        <behavior name="LegacyServiceEndpointBehavior">
          <httpUserAgent userAgent="[[[myusername:password]]]" />
        </behavior>
      </endpointBehaviors>
     </behaviors>
     <extensions>
      <behaviorExtensions>
         <add name="httpUserAgent" type="  [[[myNamespace]]].HttpUserAgentBehaviorExtensionElement, [[[myProjectName]]], Version=1.0.0.0, Cultu re=neutral, PublicKeyToken=null" />
       </behaviorExtensions>
       </extensions>
      </system.serviceModel>

3)将突出显示的文本分别更改为命名空间和项目。

4)将[[[]]]包围的以下文本添加到端点地址的末尾。这部分将需要对每项服务进行。

 <endpoint address="http://[[[ipAddress]]]/Location/GetOrderData"
            binding="basicHttpBinding" bindingConfiguration="RLCM.GetOrderDataInterfaceSoapBinding"
            contract="getOrderData.GetOrderDataInterface" name="GetOrderDataImplPort" [[[behaviorConfiguration="LegacyServiceEndpointBehavior"]]]/>


5)现在你应该可以使用这样的代码......

  Dim OrderService As getOrderData.GetOrderDataInterfaceClient = New getOrderData.GetOrderDataInterfaceClient()
  Dim returnedXML = OrderService.orderInfo("OrderNumber") and be authorized by the JBoss server and get back return data.