Wednesday, March 5, 2008

SSL HTTP POST

Hi, friends

I'm developing a module to connect C programs with WebServices and newly I've used OpenSSL. Actually it hasn't very difficult, although I had some problem. It's very important to set properly the method to use. I'm connecting with a JBoss HTTPs WebService and I had to set this one:


meth = TLSv1_client_method();
ctx = SSL_CTX_new (meth);

I copy bellow the main function I had used, to send the HTTP POST message, I hope it'll be usefull for you:

int sendPOST(void* sd, SSL* ssl, ;char* server, char* port, char* post, char* action, char* csoap, char *response){

int ret=0;
char msg[5000]="";
char buff[5000]="";
int err=0;
int len=0;
char header[200]="";

    // Setting HTTP Headers
    sprintf(msg,"POST %s HTTP/1.1\r\n", post);
    sprintf(header,"Host: %s:%s\r\n", server, port);
    len=strlen(msg) ;
    memcpy(msg + len , header, strlen(header));
    len+=strlen(header);
    strcpy(header,"Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n");
    memcpy(msg + len, header, strlen(header));
    len+=strlen(header);
    sprintf(header,"Content-Length: %d\r\n", strlen(datos));
    memcpy(msg + len, header, strlen(header));
    len+=strlen(header);
    sprintf(header,"SOAPAction: %s\r\n\r\n",action);
    memcpy(msg + len, header, strlen(header));
    len+=strlen(header);
    // Adding csoap
    memcpy(msg + len, datos, strlen(datos));

    if(sd!=NULL){
        // No SSL Connections

        err=send((int)sd, msg, len + strlen(datos),0);
        if (err == SOCKET_ERROR) {
            printf("send() failed with error: %d\n", WSAGetLastError());
            closesocket((int)sd);
            WSACleanup();
            exit(1);
        }

        do {
            err = recv((int)sd, buff, sizeof(buff) - 1, 0);
            if ( err > 0 )
                printf("Bytes received: %d\n", err);
            else if ( err == 0 )
                printf("Connection closed\n");
            else
                printf("recv failed with error: %d\n", WSAGetLastError());

        } while( err > 0 );


    }else{
        // SSL Connections
        err = SSL_write (ssl, msg, len + strlen(datos)); CHK_SSL(err);

        err = SSL_read (ssl, buff, sizeof(buff) - 1);
        CHK_SSL(err);
        buff[err] = '\0';

        SSL_shutdown (ssl);
    }

    strcpy(respuesta, buff);

    return ret;

}

No comments: