Main Content

HTTP 메시지 보내기 및 받기

이 예제에서는 리디렉션을 포함하고 다이제스트 인증을 요구할 수 있는 서버로 요청을 보내는 방법을 보여줍니다.

sendRequest 함수는 첫 번째 요청을 자동으로 리디렉션하고 이에 대한 인증을 수행합니다. 사용자는 후속 요청에서 리디렉션 비용을 또 들이고 싶지 않을 것입니다. 이를 위해 sendRequest는 이전 요청에서 받은 쿠키를 저장하여 후속 요청에 다시 사용합니다.

sendRequest는 지난 내역의 사용, 디폴트 제한 시간을 변경하기 위한 사용자 지정 HTTPOptions 객체 재사용, 그리고 저장된 자격 증명 사용을 보여줍니다.

이 예제에서는 이러한 결과를 얻기 위한 강력한 범용 메커니즘은 보여주지 않습니다. 특히, sendRequest는 도메인, 경로, 만료 또는 기타 속성에 관계없이 해당 호스트에 대한 모든 후속 메시지에 담겨 있는 호스트로부터 받은 모든 쿠키를 반환합니다. 또한, sendRequest는 MATLAB® 세션 간에 자격 증명 또는 쿠키를 저장하지 않습니다. 그럼에도 불구하고 sendRequest는 대부분의 응용 사례에 적합합니다.

다음 코드를 사용하여 sendRequest 함수를 만듭니다.

function response = sendRequest(uri,request)

% uri: matlab.net.URI
% request: matlab.net.http.RequestMessage
% response: matlab.net.http.ResponseMessage

% matlab.net.http.HTTPOptions persists across requests to reuse  previous
% Credentials in it for subsequent authentications
persistent options 

% infos is a containers.Map object where: 
%    key is uri.Host; 
%    value is "info" struct containing:
%        cookies: vector of matlab.net.http.Cookie or empty
%        uri: target matlab.net.URI if redirect, or empty
persistent infos

if isempty(options)
    options = matlab.net.http.HTTPOptions('ConnectTimeout',20);
end

if isempty(infos)
    infos = containers.Map;
end
host = string(uri.Host); % get Host from URI
try
    % get info struct for host in map
    info = infos(host);
    if ~isempty(info.uri)
        % If it has a uri field, it means a redirect previously
        % took place, so replace requested URI with redirect URI.
        uri = info.uri;
    end
    if ~isempty(info.cookies)
        % If it has cookies, it means we previously received cookies from this host.
        % Add Cookie header field containing all of them.
        request = request.addFields(matlab.net.http.field.CookieField(info.cookies));
    end
catch
    % no previous redirect or cookies for this host
    info = [];
end

% Send request and get response and history of transaction.
[response, ~, history] = request.send(uri, options);
if response.StatusCode ~= matlab.net.http.StatusCode.OK
    return
end

% Get the Set-Cookie header fields from response message in
% each history record and save them in the map.
arrayfun(@addCookies, history)

% If the last URI in the history is different from the URI sent in the original 
% request, then this was a redirect. Save the new target URI in the host info struct.
targetURI = history(end).URI;
if ~isequal(targetURI, uri)
    if isempty(info)
        % no previous info for this host in map, create new one
        infos(char(host)) = struct('cookies',[],'uri',targetURI);
    else
        % change URI in info for this host and put it back in map
        info.uri = targetURI;
        infos(char(host)) = info;
    end
end

    function addCookies(record)
        % Add cookies in Response message in history record
        % to the map entry for the host to which the request was directed.
        %
        ahost = record.URI.Host; % the host the request was sent to
        cookieFields = record.Response.getFields('Set-Cookie');
        if isempty(cookieFields)
            return
        end
        cookieData = cookieFields.convert(); % get array of Set-Cookie structs
        cookies = [cookieData.Cookie]; % get array of Cookies from all structs
        try
            % If info for this host was already in the map, add its cookies to it.
            ainfo = infos(ahost);
            ainfo.cookies = [ainfo.cookies cookies];
            infos(char(ahost)) = ainfo;
        catch
            % Not yet in map, so add new info struct.
            infos(char(ahost)) = struct('cookies',cookies,'uri',[]);
        end
    end
end

함수를 호출합니다.

request = matlab.net.http.RequestMessage;
uri = matlab.net.URI('https://www.mathworks.com/products');
response = sendRequest(uri,request)
response =   ResponseMessage with properties:

    StatusLine: 'HTTP/1.1 200 OK'
    StatusCode: OK
        Header: [1×11 matlab.net.http.HeaderField]
          Body: [1×1 matlab.net.http.MessageBody]
     Completed: 0

실제로 반환되는 응답 값은 다를 수 있습니다.

참고 항목

| | | | | |