1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "adapter/preview/osal/response_data.h"
17 
18 namespace OHOS::Ace {
19 
GetResultString() const20 std::unique_ptr<JsonValue> ResponseData::GetResultString() const
21 {
22     auto resultJson = JsonUtil::Create(true);
23     if (code_ == HTTP_OK) {
24         resultJson->Put(std::string("code").c_str(), ACTION_SUCCESS);
25         resultJson->Put(std::string("data").c_str(), GetStringValue());
26     } else {
27         resultJson->Put(std::string("code").c_str(), COMMON_ERROR_CODE);
28         resultJson->Put(std::string("data").c_str(), GetStringValue());
29     }
30 
31     return resultJson;
32 }
33 
GetStringValue() const34 std::unique_ptr<JsonValue> ResponseData::GetStringValue() const
35 {
36     auto responseJson = JsonUtil::Create(true);
37     responseJson->Put(std::string("code").c_str(), code_);
38     responseJson->Put(std::string("data").c_str(), data_.c_str());
39 
40     if (code_ == HTTP_OK) {
41         std::string headersStr = "{";
42         for (auto&& [key, value] : headers_) {
43             headersStr += key + ":" + value + ",";
44         }
45         headersStr[headersStr.size() - 1] = '}';
46         responseJson->Put(std::string("headers").c_str(), headersStr.c_str());
47     }
48     return responseJson;
49 }
50 
SetHeaders(std::string headersStr)51 void ResponseData::SetHeaders(std::string headersStr)
52 {
53     const char separator = '\n';
54     size_t posSeparator = headersStr.find(separator);
55     while (std::string::npos != posSeparator) {
56         std::string header = headersStr.substr(0, posSeparator - 1);
57         if (header == "") {
58             break;
59         }
60         size_t posColon = header.find(':');
61         if (std::string::npos == posColon) {
62             headers_["null"] = "[\"" + header + "\"]";
63         } else {
64             headers_["\"" + header.substr(0, posColon) + "\""] = "[\"" + header.substr(posColon + 2) + "\"]";
65         }
66         headersStr = headersStr.substr(posSeparator + 1);
67         posSeparator = headersStr.find(separator);
68     }
69 }
70 
GetActionCode() const71 int ResponseData::GetActionCode() const
72 {
73     if (code_ == HTTP_OK) {
74         return ACTION_SUCCESS;
75     } else {
76         return ACTION_FAIL;
77     }
78 }
79 } // namespace OHOS::Ace
80