Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Posting a document to the Webservices (REST)

Status
Not open for further replies.

Bilberry

Programmer
Dec 17, 2007
111
NL
Hi,
Does anybody know how i can upload a Word document with a XML document to the webservice? I have really tried everything, but without success. It is bad VBA coding, but im testing and hope that you can give me some hints. The JAVA code works, but not in VBA -:) I will put both codes:
Im getting a HTTP 405 error message: The specified HTTP method is not allowed for the requested resource (). Any ideas??? A golden star for the golden tip!

JAVA code example:
Code:
package com.lj.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class UploadDocumentClient {
    
    public static final String REST_SERVICE = "[URL unfurl="true"]https://{domainName}/networking/REST";[/URL]
    public static final String USER_NAME = "myusername";
    public static final String PASSWORD = "mypassword";
    
public static String login() throws Exception
    {
        
        String sessionId = null;
        
        StringBuilder loginRequestXML = new StringBuilder("<?xml version=\"1.0\" ?>")
                              .append("    mydomain ver=\"2.0\">")
                              .append ("         <login_request>")
                              .append("             <login>").append(USER_NAME).append ("</login>")
                              .append("             <password>").append(Password).append ("</password>")
                              .append ("         </login_request>")
                              .append("     </mydomain>");
        
         // Create an instance of HttpClient.
        HttpClient client = new HttpClient();
        
        //Create GET method
        PostMethod method = new PostMethod(REST_SERVICE);
        
        //add to Request
        method.addParameter("xml_data", loginRequestXML.toString());
        

         // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        
        try
        {
              // Execute the method.
              int statusCode = client.executeMethod(method);

              if (statusCode != HttpStatus.SC_OK)
              {
                System.err.println("Method failed: " + method.getStatusLine());
              }
        
              // Read the response body.
              byte[] responseBody = method.getResponseBody();
              
              String file = new String(responseBody);
              
              int indexOfXMLStart = file.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
              
              int indexOfXMLEnd = file.indexOf("</mydomain>");
                             
              String xmlPartOfResponse = file.substring(indexOfXMLStart, indexOfXMLEnd + 11);
              
              if(xmlPartOfResponse.contains("<session_id>"))
              {
              
                  int sessionIdBeginTagIndx = xmlPartOfResponse.indexOf("<session_id>");
                  
                  int sessionIdEndTagIndx = xmlPartOfResponse.indexOf("</session_id>") + "</session_id>".length();
                  
                  sessionId = (xmlPartOfResponse.substring(sessionIdBeginTagIndx, sessionIdEndTagIndx))
                                                        .replace("<session_id>", "")
                                                            .replace("</session_id>", "")
                                                                .trim();
              }
              else if (xmlPartOfResponse.contains("<error>"))
              {
                  int messageBeginTagIndx = xmlPartOfResponse.indexOf("<message>");
                  
                  int messageEndTagIndx = xmlPartOfResponse.indexOf("</message>") + "</message>".length();
                  
                  String message = (xmlPartOfResponse.substring(messageBeginTagIndx, messageEndTagIndx))
                                                        .replace("<message>", "")
                                                            .replace("</message>", "")
                                                                .trim();
                  
                  throw new Exception(message);
              }
              
        }
        catch (HttpException e)
        {
              e.printStackTrace();
              
              throw new InvocationTargetException(e, "Fatal protocol violation: " + e.getMessage());
        }
        catch (IOException e)
        {
              e.printStackTrace();
              
              throw new InvocationTargetException(e, "Fatal transport error: " + e.getMessage());
        }
        catch (Exception e)
        {
            e.printStackTrace();
              
            throw new InvocationTargetException(e, e.getMessage());
        }
        finally
        {
              // Release the connection.
              method.releaseConnection();
              
              return sessionId;
        }
    }
    
public static void pushDocumentToRemoteServer(String userName, String password, String url, String documentFileToUpload)
    {
                
                
        String sessionId = null;
        
        try
        {
            sessionId = login();
            
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        
        File targetFile = new File(documentFileToUpload);
        
        StringBuilder uploadPackageXML = new StringBuilder("<?xml version=\"1.0\" ?>")
                             .append("  <mydomain ver=\"2.0\">")
                             .append ("    <resource_upload_request>")
                             .append("      <session_id>").append(sessionId).append ("</session_id>")
                             .append ("        <type>DOCUMENTS</type>")
                             .append (" <title>Document Uploaded with out Reference</title>")
                             .append ("<description>Document upload with our reference</description>")
                             .append ("<private></private>")
                             .append ("<folder_id>bd71b54708394b788f759608e38f68e8</folder_id>")
                             .append ("<flag_public_document>1</flag_public_document>")
                             .append ("    </resource_upload_request>")
                             .append("  </mydomain>");
        
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();
        
        //Create GET method
        PostMethod method = new PostMethod(url);
        
        FilePart fp = null;
        
        StringPart sp = null;
        
        try
        {
            fp = new FilePart(targetFile.getName(), targetFile);
        }
        catch (FileNotFoundException e1)
        {
            // TODO Auto-generated catch block
            System.out.println(e1.getMessage());
        }
        
        sp= new StringPart("xml_data", uploadPackageXML.toString());
                    
        //add to Request
        Part[] parts = {fp,sp};
        
        method.setRequestEntity((RequestEntity)new MultipartRequestEntity(parts,method.getParams()));
        
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        
        try
        {
              // Execute the method.
              int statusCode = client.executeMethod(method);

              if (statusCode != HttpStatus.SC_OK)
              {
                throw new Exception("Method failed: " + method.getStatusLine());
              }
        
              // Read the response body.
              byte[] responseBody = method.getResponseBody();
              
              String file = new String(responseBody);
              
              int indexOfXMLStart = file.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
              
              int indexOfXMLEnd = file.indexOf("</mydomain>");
              
              String xmlPartOfResponse = file.substring(indexOfXMLStart, indexOfXMLEnd + 11);
              
              int messageBeginTagIndx = xmlPartOfResponse.indexOf("<message>");
              
              int messageEndTagIndx = xmlPartOfResponse.indexOf("</message>") + "</message>".length();
              
              String message = (xmlPartOfResponse.substring(messageBeginTagIndx, messageEndTagIndx))
                                        .replace("<message>", "").replace("</message>", "").trim();
              if(xmlPartOfResponse.contains("<success>"))
              {
                  System.out.println(message);
              }
              Else
              {
                  throw new Exception(message);
              }
        }
    
        catch (HttpException e)
        {
            System.out.println(e.getMessage());
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
              // Release the connection.
              method.releaseConnection();
             
        }
    }
    
public static void main(String args[])
    {
        UploadDocumentClient upc = new UploadDocumentClient();
        
        String documentLocation ="C:\\myDocument.doc";
        
        try
        {
            
            upc.pushDocumentToRemoteServer(USER_NAME, PASSWORD, REST_SERVICE,documentLocation);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}


This is the VBA example code:

Code:
Public Sub main()
    Dim query As String
    Dim strUrl As String
    Dim strAlias As String
    Dim strUserName As String
    Dim strPassWord As String
    Dim strUpload As String
    Dim myDom As MSXML2.DOMDocument
    Dim myDomResult As MSXML2.DOMDocument
    Dim objNodeList As IXMLDOMNodeList
    Dim str As String
    
    Set myDom = CreateObject("MSXML2.DOMDocument")
    Set myDomResult = CreateObject("MSXML2.DOMDocument")
    
    'Load entire Document before moving on
     myDom.async = False
    
     strWebAddress = "mydomain.com/networking/rest/"
     strUserName = "myusername"
     strPassWord = "mypassword"
     strUrl = "[URL unfurl="true"]https://"[/URL] & strWebAddress
    
    Set objHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
    
     query = "<platform><login><userName>"
     query = query + strUserName
     query = query + "</userName><password>"
     query = query + strPassWord
     query = query + "</password></login></platform>"
    
    

    objHTTP.Open "POST", strUrl & "login?alt=xml", False
    objHTTP.setRequestHeader "Content-Type", "application/xml"
    
    objHTTP.send (query)
    result = objHTTP.responseText   
    myDomResult.loadXML (result)
    Set objHTTP = Nothing
    Range("a1") = (result)



    Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")


            str = ""
            Set objNodeList = myDomResult.getElementsByTagName("sessionId")
            For i = 0 To (objNodeList.Length - 1)
               str = str & objNodeList.Item(i).XML & vbCrLf
            Next

strUpload = "<resource_upload_request>" & _
            "<?xml version=""1.0""?>" & _
            "<mydomain ver=""2.0"">" & _
            str & _
            "<type>DOCUMENTS</type>" & _
            "<title>Test Upload 2010</title>" & _
            "<description>Testing Upload Doc through REST</description>" & _
            "<private></private>" & _
            "<folder_id></folder_id>" & _
            "<flag_public_document>1</flag_public_document>" & _
            "</resource_upload_request>" & _
            "</mydomain>"

myDom.loadXML (strUpload)
Range("a3") = (myDom.XML)

Dim myFSO, f
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set f = myFSO.GetFile("C:\Test.doc")

' POST or GET???
'oXMLHTTPRequest.Open = ("POST", (myDom.XML),false)
XMLHTTP.Open "POST", strUrl, False, strUserName, strPassWord
XMLHTTP.send
result2 = XMLHTTP.responseText
'XMLHTTP.Open "PUT", f, False
'XMLHTTP.setRequestHeader "Content-Type", "application/xml"
'XMLHTTP.send (myDom.XML)
'result2 = XMLHTTP.responseText

Range("a2") = (result2)


End Sub
 
Hi,
Range("a2") = (result2)

Main question is: How to upload a file, where to put that information?? Behind send or behind .Open "POST
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top