Use REST service via a proxy server with socket(C)
From WABI
Contents |
Summary
Use REST service via a proxy server with socket (C)
Description
To use proxy with socket, specify REST service's URL after making socket connection to proxy server.
struct sockaddr_in server; // set proxy server char proxy_host[BUF_LEN] = "<proxy_server>"; unsigned short proxy_port = <proxy_port>; char url[BUF_LEN] = "http://xml.nig.ac.jp/rest/Invoke"; // make socket and connection servhost = gethostbyname(proxy_host); bzero(&server, sizeof(server); server.sin_family = AF_INET; bcopy(servhost->h_addr, &server.sin_addr, servhost->h_length); server.sin_port = htons(proxy_port); s = socket(AF_INET, SOCK_STREAM, 0); connect(s, (struct sockaddr *)&server, sizeof(server)); //send data sprintf(send_buf, "POST %s HTTP/1.0\n", url); write(s, send_buf, strlen(send_buf));
Sample program
This program executes getDDBJEntryof GetEntry via a proxy server with socket of C.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/param.h>
#include <sys/uio.h>
#include <unistd.h>
#define BUF_LEN 256
int main(){
int s;
struct hostent *servhost;
struct sockaddr_in server;
struct servent *service;
char send_buf[BUF_LEN];
//set proxy server
char proxy_host[BUF_LEN] = "<proxy_server>";
unsigned short proxy_port = <proxy_port>;
//set API server
char url[BUF_LEN] = "http://xml.nig.ac.jp/rest/Invoke";
char query[BUF_LEN] = "service=GetEntry&method=getDDBJEntry&accession=AB000200";
//make socket
servhost = gethostbyname(proxy_host);
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
bcopy(servhost->h_addr, &server.sin_addr, servhost->h_length);
server.sin_port = htons(proxy_port);
s = socket(AF_INET, SOCK_STREAM, 0);
//make connection
connect(s, (struct sockaddr *)&server, sizeof(server));
//send data
sprintf(send_buf, "POST %s HTTP/1.0\n", url);
write(s, send_buf, strlen(send_buf));
sprintf(send_buf, "Host: %s:%d\n", proxy_host, proxy_port);
write(s, send_buf, strlen(send_buf));
sprintf(send_buf, "Content-Type: application/x-www-form-urlencoded\n");
write(s, send_buf, strlen(send_buf));
sprintf(send_buf, "User-Agent: c/socket\n");
write(s, send_buf,strlen(send_buf));
sprintf(send_buf, "Content-Length: %d \n\n", strlen(query));
write(s, send_buf, strlen(send_buf));
sprintf(send_buf, "%s", query);
write(s, send_buf, strlen(send_buf));
//get your result
while (1){
char buf[BUF_LEN];
int read_size;
read_size = read(s, buf, BUF_LEN);
if ( read_size > 0 ){
write(1, buf, read_size);
} else {
break;
}
}
close(s);
return 0;
}
