Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > Вызов с JSP .NET WebService


Автор: deviantus 12.2.2007, 18:33
Нужно вызвать .NET WebService через JSP страничку.
Делаю все как описано тут:
http://www.c-sharpcorner.com/UploadFile/ankithakur/WSIntegration02132006041221AM/WSIntegration.aspx?ArticleID=a0966837-4a15-4091-b6a7-a751ed3ada85
Все работает, если сервис без авторизации.

Но мне нужно получить доступ к веб-сервису под Windows авторизацией.

Как авторизировать?  smile 

Автор: deviantus 13.2.2007, 20:01
Проблема решена! Накодил вот такое:

Код

package NETWebServiceConnector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

// Use Apache HTTPclient package
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * This Class call a .NET WebService with NTLM authentication
 */
public class NETWebServiceConnector {

    // WebService URL
    private String webServiceURL;
    
    // WebService namespace
    private String webServiceNamespace;
    
    // WebService method answer
    private String webServiceAnswer;
    
    // HTTP Client object
    private HttpClient client = new HttpClient();
    
    // Constructor initialize fields
    public NETWebServiceConnector(String wsURL, String wsNamespace) {
        this.webServiceURL = wsURL;
        this.webServiceNamespace = wsNamespace;
    }

    // Provide NTLMA authentication
    public void NTLMAuthorise(String authUser, String authPassword, String authHostname, String authDomain) {
        // Create credentials
        Credentials credentials = new NTCredentials(authUser, authPassword, authHostname, authDomain);
        
        // Set authentication type
        List authPrefs = new ArrayList(1);
        authPrefs.add(AuthPolicy.NTLM);
        client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        client.getParams().setAuthenticationPreemptive(true);
        
        // Set credentials
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    // Return WebService method response
    public String getResponse() {
        return this.webServiceAnswer;
    }
    
    // Call WebService Method with parameters
    public String executeMethod(String webServiceMethod, String[] webServiceParameters, String[] webServiceValues) {
     // Use POST request method
     PostMethod method = new PostMethod(this.webServiceURL);
     
     // Add to headers SOAPAction
     method.addRequestHeader("SOAPAction", '"' + this.webServiceNamespace + '/' + webServiceMethod + '"');
     
     // Add to headers correct content type
     method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");

     // Generate SOAP request
     String SOAPRequest = "";
     
     SOAPRequest += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
     SOAPRequest += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n";
     SOAPRequest += "<soap:Body>\n";
     
     SOAPRequest += "<" + webServiceMethod + " xmlns=\"" + this.webServiceNamespace + "\">\n";

        // Put WebService method parameters and values
        for (int i = 0; i < webServiceParameters.length; i++)
        {
            SOAPRequest += ("<" + webServiceParameters[i] + ">" + webServiceValues[i] + "</" + webServiceParameters[i] + ">\n");
        }

     SOAPRequest += "</" + webServiceMethod + ">\n";

     SOAPRequest += "</soap:Body>\n";
     SOAPRequest += "</soap:Envelope>";
     
     // Set correct content length
     method.setRequestContentLength(SOAPRequest.length());
     
     // Put SOAP request to HTTP POST request body
     method.setRequestBody(SOAPRequest);

        try {
            // Execute the POST method
            int statusCode = client.executeMethod(method);

            // Check HTTP response code
            if (statusCode != HttpStatus.SC_OK) {
             return "Method failed: " + method.getStatusLine();
            }
            
            // Read the response body
            byte[] responseBody = method.getResponseBody();
            String answer = new String(responseBody);
            
            // Get method result
            String methodTagResult = webServiceMethod + "Result";
            
            int startPosResult = answer.indexOf("<" + methodTagResult + ">");
            int endPosResult = answer.indexOf("</" + methodTagResult + ">");
            
            if (startPosResult != -1 && endPosResult != -1) {
                startPosResult += methodTagResult.length() + 2;
                this.webServiceAnswer = answer.substring(startPosResult, endPosResult);
            }
            else {
             this.webServiceAnswer = answer;
            }

            return "WebService called successfully.";
        } catch (HttpException e) {
           return "Fatal protocol violation: " + e.getMessage();
        } catch (IOException e) {
           return "Fatal transport error: " + e.getMessage();
        } finally {
           method.releaseConnection();
        }
    }
}


Елси есть что прокомментировать - пишите! ;)

Автор: AntonioBanderaz 14.2.2007, 02:13
deviantus, зачем формировать SOAP пакет руками... есть же AXIS... wsdl2java сгенерит проксю для этого сервиса, в которую ты уже сам добавишь что нужно... 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)