B4J Question HTTP Post [SOLVED]

moore_it

Well-Known Member
Licensed User
Longtime User
Hi all,

how i do for posting a file on https server ?

I try with Httpjob but not work this is the errormessage.

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

this is my code ...

B4X:
mHTTP.Initialize("HTTP", Me)
        mHTTP.Username = data(4)
        mHTTP.Password = data(5)
        mHTTP.PostString(data(3),msg)

where: data(4) = username, data(5) = password, data(3) = server address, msg = string data
 
Last edited:

moore_it

Well-Known Member
Licensed User
Longtime User
Thanks Erel,

it's possible to post a string ?
Convert a map to byte flow but it's not a valid type for target server.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
it's possible to post a string ?
sure
Convert a map to byte flow but it's not a valid type for target server.
Use jsongenerator to convert the Map to a jsonstring.
Post this json then.

If that does not work you should post DOCUMENTATION of the used api.
Without knowing what they expect noone can help you.
 
Upvote 0

moore_it

Well-Known Member
Licensed User
Longtime User
I need to post a file to UPS server
B4X:
Dim by As InputStream
by = File.OpenInput(data(1),filename)
   
Dim ff As String
    Dim tr As TextReader
    tr.Initialize2(File.OpenInput(data(1),filename),"UTF-8")
    ff = tr.ReadAll
    tr.Close
   


    Dim msg As Map
    msg.Initialize
    msg.Put("01","POST /hapld/tos/kdwhapltos HTTP/1.1"&CRLF)
    msg.Put("02","Host: www.pld-certify.ups.com"&CRLF)
    msg.Put("03","Content-type: multipart/mixed; boundary=BOUNDARY"&CRLF)
    msg.Put("04","Content-length: " & lenght &CRLF)
    msg.Put("05",CRLF)
    msg.Put("06","--BOUNDARY"&CRLF)
    msg.Put("07","Content-type: application/x-www-form-urlencoded"&CRLF)
    msg.Put("08","Content-length: 136"&CRLF)
    msg.Put("09",CRLF)
    msg.Put("10","AppVersion=1.0&AcceptUPSLicenseAgreement=Yes&ResponseType=application/x-ups-pld&VersionNumber=V4R1&UserId=" & data(4) & "&Password=" & data(5) &CRLF)
    msg.Put("11",CRLF)
    msg.Put("12","--BOUNDARY"&CRLF)
    msg.Put("13","Content-type: application/x-ups-binary"&CRLF)
    
    msg.Put("14",ff&CRLF)
    
    msg.Put("15",CRLF)
    msg.Put("16","--BOUNDARY--"&CRLF)
    
    Dim ser As B4XSerializator
    Dim b() As Byte = ser.ConvertObjectToBytes(msg)
    
    Try
        mHTTP.InitializeAcceptAll("HTTPS")
        Dim req As OkHttpRequest
        req.InitializePost2(data(3),b)
        mHTTP.Execute(req,1000)    
        ListView2.Items.Add(Chr(0xF05A)&" File inviato correttamente !")
    Catch        
        ListView2.Items.Add(Chr(0xF071)&" Errore nell'invio del file !")
        If controller <> "" Then
            ControlMail(action,controller,Chr(0xF071)&BytesToString(out.ToBytesArray, 0, out.ToBytesArray.Length, "utf8"))
        End If
    End Try
    End Try

with byte the response is :

--BOUNDARY
Content-type: text/html
Content-length: 138

<HTML>
<HEAD>
<TITLE>UPS Internet Software</TITLE>
</HEAD>
<BODY>
<P>UPS Internet Software, Copyright UPS 1998</P>
</BODY>
</HTML>

--BOUNDARY
Content-type: application/x-ups-psmpld
Content-length: 104

UPSOnLine%null%6931%6811Content-Type invalid.

--BOUNDARY
Content-type: application/x-ups-pld
Content-length: 110

00010000009710000008800026811Content-Type invalid.

--BOUNDARY--

( in another language use string in post command and work fine ).

Thanks for your help.
 
Upvote 0

moore_it

Well-Known Member
Licensed User
Longtime User
B4X:
Dim msg As Map
    msg.Initialize
    msg.Put("01","POST /hapld/tos/kdwhapltos HTTP/1.1"&CRLF)
    msg.Put("02","Host: www.pld-certify.ups.com"&CRLF)
    msg.Put("03","Content-type: multipart/mixed; boundary=BOUNDARY"&CRLF)
    msg.Put("04","Content-length: " & lenght &CRLF)
    msg.Put("05",CRLF)
    msg.Put("06","--BOUNDARY"&CRLF)
    msg.Put("07","Content-type: application/x-www-form-urlencoded"&CRLF)
    msg.Put("08","Content-length: 136"&CRLF)
    msg.Put("09",CRLF)
    msg.Put("10","AppVersion=1.0&AcceptUPSLicenseAgreement=Yes&ResponseType=application/x-ups-pld&VersionNumber=V4R1&UserId=" & data(4) & "&Password=" & data(5) &CRLF)
    msg.Put("11",CRLF)
    msg.Put("12","--BOUNDARY"&CRLF)
    msg.Put("13","Content-type: application/x-ups-binary"&CRLF)
    
    'msg.Put("14",ff&CRLF)
    
    msg.Put("15",CRLF)
    msg.Put("16","--BOUNDARY--"&CRLF)
Try
        mHTTP.Initialize("HTTPS",Me)
        Dim fd As MultipartFileData
        fd.Initialize
        fd.KeyName = "PLDFILE"
        fd.Dir = data(1)
        fd.FileName = filename
        Dim L As List
        L.Initialize
        L.Add(fd)
        mHTTP.PostMultipart(data(3),msg,l)
    Catch       
        Log(LastException.Message)
    End Try

error :

ResponseError. Reason: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target, Response:
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
these code can not be valid to work with UPS. i´m pretty sure it is the wrong approach.

Check the UPS-Dcumentation on how it must be done.

What API exactly you are trying to implement? Post a link to the documentation please.
 
Upvote 0

moore_it

Well-Known Member
Licensed User
Longtime User
Have this in Java

B4X:
package electronicmanifesting;

import java.io.*;
import java.util.*;
import java.net.*;
import java.security.*;
import com.sun.net.ssl.internal.www.protocol.https.*;
import java.security.Security;
import javax.net.ssl.*;


public class URLConClient {



public URLConClient() {
    super();
}

/**
 * Starts the application.
 * @param args an array of command-line arguments
 * @throws Exception IOException(e)
 */
public static void main(String[] args) throws Exception {


  if (args.length == 0) {
     System.out.println("Usage: java electronicmanifesting.URLConClient Filename");
     return;
     }


    try{
// Certification Environment
      String pld_url="https://www.pld-certify.ups.com/hapld/tos/kdwhapltos ";
        String CRLF = "\r\n";
        String HTTPversion = "HTTP/1.1"; // For SPF5.x - SPF7 uploads use HTTP/1.0
    File f=new File(args[0]);
    long fileLength=f.length();

        String Seperator  =   "--BOUNDARY" + CRLF;
        String requestEnd =   CRLF + CRLF + "--BOUNDARY--" + CRLF;

/**
 * First Data Segment (Construction of Data-String and Header)
 * The "Content-type" of the first data segment is application/x-www-form-urlencoded.
 * According to this definition the following Values must be URL encoded.
 */
        String userId=java.net.URLEncoder.encode("PLDDSTEST");
    String password=java.net.URLEncoder.encode("PLDDSTEST");
    String versionNumber=java.net.URLEncoder.encode("V4R1");
    String responseType="application/x-ups-pld";
    String appVersion=java.net.URLEncoder.encode("1.0");
    String acceptUPSLicenseAgreement=java.net.URLEncoder.encode("Yes");


    String FirstDataSegment =   "AppVersion=" + appVersion +
                                "&AcceptUPSLicenseAgreement=" + acceptUPSLicenseAgreement +
                                "&ResponseType=" + responseType +
                                "&VersionNumber=" + versionNumber+
                                "&UserId=" + userId +
                                "&Password=" + password;

    String FirstDataSegmentHeader =   "Content-type: application/x-www-form-urlencoded" + CRLF +
                                      "Content-length: " + FirstDataSegment.length() + CRLF + CRLF;


/**
 * Second Data Segment (Construction of Data-String and Header)
 * The "Content-type" of the first data segment is application/x-ups-binary.
 * According to this definition the following Values must NOT be URL encoded.
 */

/**
 * The SecondDataSegment is the Content of the PLD File
 */
    String SecondDataSegmentHeader =  "Content-type: application/x-ups-binary" + CRLF +
                                      "Content-length: " + fileLength + CRLF + CRLF;

/**
 * Main Header
 * The "Content-type" of Main Header is "multipart/mixed; boundary=BOUNDARY".
 * According to this definition the following Values must NOT be URL encoded.
 */
    String MainHeader=    "URL " +  pld_url + HTTPversion + CRLF +
                          "Content-type: multipart/mixed; boundary=BOUNDARY" + CRLF +

                          //-------------------------------------------------------------
                          // calculation of the Content-length according to the
                          // "Example of a Request Message" in the Electronic Manifesting
                          // documentation 
                          "Content-length: " + (Seperator.length()
                                             + FirstDataSegmentHeader.length()
                                             + FirstDataSegment.length()
                                             + CRLF.length() + CRLF.length()
                                             + Seperator.length()
                                             + SecondDataSegmentHeader.length()
                                             + fileLength
                                             + requestEnd.length())

                         //-------------------------------------------------------------- 
                                             + CRLF  + CRLF; // not belonging to the calculation

/**
 * Establish a SSL URLConnection with the JSSE Package
 * and send Outputstream to UPS
 */
    System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());


           URL url=new URL(pld_url);
            URLConnection connection=url.openConnection();
           connection.setAllowUserInteraction(true);
          connection.setDoInput(true);
           connection.setDoOutput(true);
          connection.setUseCaches(false);

                // Use the Content-type "multipart/mixed; boundary=BOUNDARY" in the MainHeader
                connection.setRequestProperty("Content-type", "multipart/mixed; boundary=BOUNDARY");


      // new BufferedWriter out 
      Writer out=new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));


/**
 * Send first Part (MainHeader, FirstDataSegment, FirstDataSegmentHeader
 * and SecondDataSegmentHeader) to the Outputstream
 */

        out.write(MainHeader);
        System.out.print(MainHeader);

        out.write(Seperator);
        System.out.print(Seperator);

        out.write(FirstDataSegmentHeader);
        System.out.print(FirstDataSegmentHeader);

        out.write(FirstDataSegment);
        System.out.print(FirstDataSegment);


        out.write(CRLF);
        System.out.print(CRLF);

        out.write(CRLF);
        System.out.print(CRLF);

        out.write(Seperator);
        System.out.print(Seperator);

        out.write(SecondDataSegmentHeader);
        System.out.print(SecondDataSegmentHeader);


/**
 * Send SecondDataSegment:
 * Open PLD File(args[0]) with FileReader and
 * send content to the Outputstream
 */
      try {
      int i=0;
      FileReader fr=new FileReader(f);
      while (i!= -1)
        {
        i=fr.read();
        if (i!= -1)
            {
        out.write((char)i);
            System.out.print((char)i);
        }
          }
      fr.close();
        }
      catch (IOException ioe) {
      System.out.println("IOException!");
      }

/**
 * Send requestEnd to the Outputstream
 */
        out.write(requestEnd);
        System.out.println(requestEnd);

/**
 * Send all left buffered Data to the Outputstream
 */ 
        out.flush();
/**
 * read InputStream from the URLConnection and show UPS Response
 */
        String inputLine;
    BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));

// get ContentType and ContentLength from the MainHeader of the UPS Response
        System.out.println("Content-Type: " + connection.getContentType());
        System.out.println("Content-Length: " + connection.getContentLength());
        System.out.println("\r\n");

// Printout of the InputStream 
        while((inputLine=in.readLine())!=null)
        {
            System.out.println(inputLine);
        }
        in.close();
    }


    catch (IOException e) {
        System.err.println("Exception trying to make URL connection");
                System.err.println(e);
    }


 }
}
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Can't test. The code may look something like this.

B4X:
Sub UploadFile
    'Try
        Dim fd As MultipartFileData
        fd.Initialize
        fd.Dir = "C:\temp"
        fd.FileName = "sample.txt"
        'fd.KeyName = "file"
        'fd.ContentType = "application/octet-stream"
        'fd.ContentType = "application/x-ups-binary"
        fd.ContentType = "multipart/mixed; boundary=BOUNDARY"
       
        'Dim Params1 As Map
        'Params1.Initialize
        'Params1.Put("file": "sample.txt")
        Dim File1 As List
        File1.Initialize
        File1.Add(fd)
       
        Dim job As HttpJob
        job.Initialize("", Me)
        'job.PostMultipart("https://www.pld-certify.ups.com/hapld/tos/kdwhapltos", Params1, File1)
        job.PostMultipart("https://www.pld-certify.ups.com/hapld/tos/kdwhapltos", Null, File1)
        Log("Uploading file...")
        Wait For (job) JobDone(job As HttpJob)
        If job.Success Then
            Log("Success: " & job.GetString)
        Else
            Log("Failed: " & job.ErrorMessage)
        End If
    'Catch
    '    Log("Error: " & LastException.Message)
    'End Try
    job.Release
End Sub
 
Upvote 0

moore_it

Well-Known Member
Licensed User
Longtime User
Hi, thanks anyway for your help!

I've also tried this method but have ever this error

Failed: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

always using Httjob
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Not sure.
I just tried to run my code. I get a Success response.

 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…