2013-06-29 2 views
2

Я пытаюсь использовать KSOAP2 с базовой аутентификацией. Я загружаю ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar, ksoap2-extras-3.0.0.jar, ksoap2-extra-ntlm-3.0.0.jar. Я пытался использовать код ниже:Ksoap 3.0.0 не работает с базовой аутентификацией

ArrayList<HeaderProperty> headerProperty = new ArrayList<HeaderProperty>(); 
headerProperty.add(new HeaderProperty("Authorization", "Basic " + 
org.kobjects.base64.Base64.encode("user:password".getBytes()))); 

это генерировать ошибку:

java.io.IOException: HTTP request failed, HTTP status: 401 
ERROR:java.io.IOException:HTTP request failed, HTTP status: 401 

Я пытался использовать этот код тоже:

HttpTransportBasicAuth androidHttpTpAut = new HttpTransportBasicAuth(URL, "user", "password"); 
androidHttpTpAut.getServiceConnection().connect(); 

снова не работает, генерировать ошибку :

Exception in thread "main" java.lang.NoClassDefFoundError: org/ksoap2/transport/HttpTransport 
    at java.lang.ClassLoader.defineClass1(Native Method) 

Кто-нибудь это делает fi ne?

ответ

4

После многих испытаний, я обнаружил, что ниже код нужно изменить:

ArrayList headerProperty = new ArrayList(); 
headerProperty.add(new HeaderProperty("Authorization", "Basic " + 
org.kobjects.base64.Base64.encode("user:password".getBytes()))); 

androidHttpTransport.call(SOAP_ACTION, envelope); 

Изменение выше androidHttpTransport.call() ниже полиморфного метода:

androidHttpTransport.call(SOAP_ACTION, envelope, headerProperty); 

подмигнули необходимым поставить параметр headerProperty в методе androidHttpTransport.call. И, я использую только ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar в проекте.

Thanks

+0

принять этот ответ как лучший ответ. – Tupac

+0

Работает как очарование! – CGR

1

Вы можете попробовать следующий код. Он работал в моем случае, надеюсь, что это тоже поможет.

Создайте класс HttpTransportBasicAuth

import org.ksoap2.transport.*; 
import org.ksoap2.transport.HttpTransportSE; 
import java.io.*; 

public class HttpTransportBasicAuth extends HttpTransportSE { 
    private String username; 
    private String password; 

    public HttpTransportBasicAuth(String url, String username, String password) { 
     super(url); 
     this.username = username; 
     this.password = password; 
    } 

    public ServiceConnection getServiceConnection() throws IOException { 
     ServiceConnectionSE midpConnection = new ServiceConnectionSE(url); 
     addBasicAuthentication(midpConnection); 
     return midpConnection; 
    } 

    protected void addBasicAuthentication(ServiceConnection midpConnection) throws IOException { 
     if (username != null && password != null) { 
      StringBuffer buf = new StringBuffer(username); 
      buf.append(':').append(password); 
      byte[] raw = buf.toString().getBytes(); 
      buf.setLength(0); 
      buf.append("Basic "); 
      org.kobjects.base64.Base64.encode(raw, 0, raw.length, buf); 
      midpConnection.setRequestProperty("Authorization", buf.toString()); 
     } 
    } 
} 

, а затем измените следующие в классе прокси (см прокси-класс ниже)

protected org.ksoap2.transport.Transport createTransport() 
{ 
    return new HttpTransportBasicAuth(url,username,password); 
} 

прокси-класс

import java.util.List; 

import org.ksoap2.HeaderProperty; 
import org.ksoap2.SoapFault; 
import org.ksoap2.serialization.AttributeContainer; 
import org.ksoap2.serialization.PropertyInfo; 
import org.ksoap2.serialization.SoapObject; 

public class Z_WS_SCAN_REPLENISHMENT 
{ 
    interface IWcfMethod 
    { 
     ExtendedSoapSerializationEnvelope CreateSoapEnvelope() throws java.lang.Exception; 

     Object ProcessResult(ExtendedSoapSerializationEnvelope envelope,SoapObject result) throws java.lang.Exception; 
    } 

    String url="http://example.com/z_ws_scan_replenishment/200/z_ws_scan_replenishment/z_ws_scan_replenishment"; 
    String username = "username"; 
    String password = "password"; 

    int timeOut=60000; 
    public List< HeaderProperty> httpHeaders; 

    IServiceEvents callback; 
    public Z_WS_SCAN_REPLENISHMENT(){} 

    public Z_WS_SCAN_REPLENISHMENT (IServiceEvents callback) 
    { 
     this.callback = callback; 
    } 
    public Z_WS_SCAN_REPLENISHMENT(IServiceEvents callback,String url) 
    { 
     this.callback = callback; 
     this.url = url; 
    } 

    public Z_WS_SCAN_REPLENISHMENT(IServiceEvents callback,String url,int timeOut) 
    { 
     this.callback = callback; 
     this.url = url; 
     this.timeOut=timeOut; 
    } 

    protected org.ksoap2.transport.Transport createTransport() 
    { 
     return new HttpTransportBasicAuth(url,username,password); 
    } 

    protected ExtendedSoapSerializationEnvelope createEnvelope() 
    { 
     return new ExtendedSoapSerializationEnvelope(); 
    } 

    protected void sendRequest(String methodName,ExtendedSoapSerializationEnvelope envelope,org.ksoap2.transport.Transport transport) throws java.lang.Exception 
    { 
     transport.call(methodName, envelope,httpHeaders); 
    } 

    Object getResult(Class destObj,SoapObject source,String resultName,ExtendedSoapSerializationEnvelope __envelope) throws java.lang.Exception 
    { 
     if (source.hasProperty(resultName)) 
     { 
      Object j=source.getProperty(resultName); 
      if(j==null) 
      { 
       return null; 
      } 
      Object instance=__envelope.get((AttributeContainer)j,destObj); 
      return instance; 
     } 
     else if(source.getName().equals(resultName)) { 
      Object instance=__envelope.get(source,destObj); 
      return instance; 
     } 
     return null; 
    } 


    public Bapireturn1 ZScanReplenishment(final String ILgnum,final String IPernr,final String IScannedId,final String IScannedLgpl) throws java.lang.Exception 
    { 
     return (Bapireturn1)execute(new IWcfMethod() 
     { 
      @Override 
      public ExtendedSoapSerializationEnvelope CreateSoapEnvelope(){ 

       ExtendedSoapSerializationEnvelope __envelope = createEnvelope(); 
       SoapObject __soapReq = new SoapObject("urn:sap-com:document:sap:soap:functions:mc-style", "ZScanReplenishment"); 
       __envelope.setOutputSoapObject(__soapReq); 



       PropertyInfo __info=null; 
       __info = new PropertyInfo(); 
       __info.namespace=""; 
       __info.name="ILgnum"; 
       __info.type=PropertyInfo.STRING_CLASS; 
       __info.setValue(ILgnum); 
       __soapReq.addProperty(__info); 
       __info = new PropertyInfo(); 
       __info.namespace=""; 
       __info.name="IPernr"; 
       __info.type=PropertyInfo.STRING_CLASS; 
       __info.setValue(IPernr); 
       __soapReq.addProperty(__info); 
       __info = new PropertyInfo(); 
       __info.namespace=""; 
       __info.name="IScannedId"; 
       __info.type=PropertyInfo.STRING_CLASS; 
       __info.setValue(IScannedId); 
       __soapReq.addProperty(__info); 
       __info = new PropertyInfo(); 
       __info.namespace=""; 
       __info.name="IScannedLgpl"; 
       __info.type=PropertyInfo.STRING_CLASS; 
       __info.setValue(IScannedLgpl); 
       __soapReq.addProperty(__info); 
       return __envelope; 
      } 

      @Override 
      public Object ProcessResult(ExtendedSoapSerializationEnvelope __envelope,SoapObject __result)throws java.lang.Exception { 
       return (Bapireturn1)getResult(Bapireturn1.class,__result,"EReturn",__envelope); 
      } 
     },""); 
    } 



    protected Object execute(IWcfMethod wcfMethod,String methodName) throws java.lang.Exception 
    { 
     org.ksoap2.transport.Transport __httpTransport=createTransport(); 
     ExtendedSoapSerializationEnvelope __envelope=wcfMethod.CreateSoapEnvelope(); 
     sendRequest(methodName, __envelope, __httpTransport); 
     Object __retObj = __envelope.bodyIn; 
     if (__retObj instanceof SoapFault){ 
      SoapFault __fault = (SoapFault)__retObj; 
      throw convertToException(__fault,__envelope); 
     }else{ 
      SoapObject __result=(SoapObject)__retObj; 
      return wcfMethod.ProcessResult(__envelope,__result); 
     } 
    } 

    java.lang.Exception convertToException(SoapFault fault,ExtendedSoapSerializationEnvelope envelope) 
    { 
     return new java.lang.Exception(fault.faultstring); 
    } 
} 

Эти изменения сделали магию для меня , Надеюсь, это сработает и для вас.

Смежные вопросы