2 catstoryforit CatstoryforIT 于 2017.08.28 18:54 提问

ubuntu终端,发送http请求获取天气,得到服务器回应的问题。求大神解惑!

我执行程序后,获得天气的信息。但是JOSN数据后面还带有一些不必要的信息,这是为什么。 我的的是ubuntu16.04的。执行结果图片和代码如下。
图片说明

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define MAX_SIZE (4028u)

int main(int argc, char const *argv[])
{
    struct hostent *p = gethostbyname("weather.market.alicloudapi.com");
    struct in_addr **list = (struct in_addr **)p->h_addr_list;

    int fd = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in srvaddr;
    socklen_t len = sizeof(srvaddr);
    bzero(&srvaddr,len);

    srvaddr.sin_family = AF_INET;
    srvaddr.sin_port = htons(atoi(argv[1]));
    srvaddr.sin_addr.s_addr = inet_addr(inet_ntoa(*list[0]));

    int i;
    for(i=0; p->h_addr_list[i]!=NULL; i++)
    {
        printf("%s\n", inet_ntoa( *list[i]) );
    }

    char *r_buf = calloc(1,MAX_SIZE);
    char *w_buf = calloc(1,1024);

    bzero(w_buf,1024);  
    snprintf(w_buf,1024,"GET /phone-post-code-weeather?"
                        "phone_code=020 "
                        "HTTP/1.1\r\n"
                        "Host:weather.market.alicloudapi.com\r\n"
                      "Authorization:APPCODE be474d3c8ec84316b1e***7298d8123b\r\n\r\n");


    connect(fd,(struct sockaddr *)&srvaddr,len);
    write(fd,w_buf,1024);

    int ret = 0;
    int pianyi = 0;

    do{
        ret = read(fd,r_buf + pianyi,1);
        pianyi += ret;
    }
    while(ret > 0);

    printf("%s\n",r_buf);

    close(fd);
    return 0;
}
Csdn user default icon
上传中...
上传图片
插入图片