TangCheng
2025-02-28 d787e447e95c7b897c2cc9c0e832f8d2e5084934
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package com.smtscript.lib.http;
 
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
 
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeFunction;
import org.mozilla.javascript.NativeObject;
 
import com.smtscript.lib.JSComment;
import com.smtscript.lib.JSStaticHttp;
import com.smtscript.run.ScriptRunScope.FileInfo;
import com.smtscript.utils.HttpClient;
import com.smtscript.utils.HttpClient.HttpClientNotify;
import com.smtscript.utils.HttpClient.HttpClientPostFile;
import com.smtscript.utils.JSCommentDoc;
import com.smtscript.utils.SMTStatic;
 
public class JSHttpClient 
{
    protected HttpClient _httpClient = new HttpClient();
    protected JSStaticHttp _parentHttp; 
    
    public JSHttpClient(JSStaticHttp parentHttp)
    {
        _parentHttp = parentHttp;
    }
    
    public NativeObject getCookies(String url) throws Exception
    {
        NativeObject nv = new NativeObject();
        Map<String, HttpCookie> mapCookie = _httpClient.getCookies(url);
        if(mapCookie != null)
        {
            for(Entry<String, HttpCookie> entry : _httpClient.getCookies(url).entrySet())
            {
                SMTStatic.putJSNotNullValue(nv, entry.getKey(), entry.getValue().getValue());
            }
        }
        return nv;
    }
    
    public void setCookies(String url, String[] cookies) throws Exception
    {
        _httpClient.setCookies(url, cookies);
    }
    
    public void setCookies(String url, String cookies) throws Exception
    {
        List<String> list = new ArrayList<String>();
        for(String cookie : cookies.split(";\\s*"))
        {
            String[] sp = cookie.split("=", 2);
            if(sp.length != 2)
                continue;
            list.add(sp[0].trim());
            list.add(sp[1].trim());
        }
        setCookies(url, list.toArray(new String[list.size()]));
    }
    
    @JSComment(
        JSCommentDoc.HTTP_QUERY_URL
    )
    public Document queryHttpXml(Object url) throws Exception
    {
        String ret = queryHttpString(url);
        ByteArrayInputStream bis = new ByteArrayInputStream(ret.getBytes("UTF-8"));
        SAXReader reader = new SAXReader();
        Document document = reader.read(bis);
        
        return document;
    }
    
    @JSComment(
        JSCommentDoc.HTTP_QUERY_URL
    )
    public String queryHttpString(Object url) throws Exception
    {
        String encode = "UTF-8";
        
        if(url instanceof NativeObject)
        {
            NativeObject nvURL = (NativeObject) url;
            encode = (String) SMTStatic.getJSValue(nvURL, "encode", encode);
        }
        byte[] data = queryHttpBytes(url);
        String ret = new String(data, encode);
        return ret;
    }
    
    @JSComment(
        JSCommentDoc.HTTP_QUERY_URL
    )
    public void queryHttpFile(Object url, String fileName) throws Exception
    {
        FileOutputStream fos = new FileOutputStream(fileName);
        try
        {
            fos.write(queryHttpBytes(url));
        }
        finally
        {
            fos.close();
        }
    }
 
    
    private byte[] queryHttpBytes(Object url) throws Exception
    {
        url = SMTStatic.unwrapObject(url);
        final Context cx = _parentHttp.__parentScope__().__runtime__().entryContext();
        
        try
        {
            String encode = "UTF-8";
            String method = "GET";
            String sUrl = null;
            String sBody = null;
            String[] params = null;
            String[] heads  = null;
            String[] cookies= null;
            HttpClientNotify notify = null;
            HttpClientPostFile[] files = null;
            if(url instanceof String)
            {
                method = "GET";
                sUrl = (String)url;
            }
            else if(url instanceof NativeObject)
            {
                NativeObject nvURL = (NativeObject) url;
                method = (String) SMTStatic.getJSValue(nvURL, "method", "POST");
                sUrl = (String) SMTStatic.getJSValue(nvURL, "url");
                sBody = (String)SMTStatic.getJSValue(nvURL, "body", null);
                params = convNativeObjecToStringArray((NativeObject) nvURL.get("params"));
                heads = convNativeObjecToStringArray((NativeObject) nvURL.get("heads"));
                cookies = convNativeObjecToStringArray((NativeObject) nvURL.get("cookies"));
                encode = (String) SMTStatic.getJSValue(nvURL, "post_encode", encode);
    
                final NativeFunction traceFunc = (NativeFunction) SMTStatic.getJSValue(nvURL, "trace", null);
                if(traceFunc != null)
                {
                    if(notify == null)
                    {
                        notify= new HttpClientNotify(){
    
                            @Override
                            public void send(HttpURLConnection conn, String body) {
                                traceFunc.call(cx, traceFunc, null, new Object[]{"SEND", body, conn});
                            }
    
                            @Override
                            public void receive(HttpURLConnection conn, String recv) {
                                traceFunc.call(cx, traceFunc, null, new Object[]{"RECV", recv, conn});
                            }
                        };
                    }
                }
                
                if(cookies != null)
                {
                    this.setCookies(sUrl, cookies);
                }
                
                NativeObject nvFiles = (NativeObject) nvURL.get("files");
                if(nvFiles != null)
                {
                    List<HttpClientPostFile> list = new ArrayList<HttpClientPostFile>();
                    method = "FILE";
                    try
                    {
                        for(Entry<Object, Object> entry : nvFiles.entrySet())
                        {
                            String fileId = (String) entry.getKey();
                            Object fileName = entry.getValue();
                            if(fileName instanceof String)
                            {
                                FileInfo file = this._parentHttp.__parentScope__().__findExistFile__((String)fileName, true);
                                HttpClientPostFile postFile = new HttpClientPostFile(fileId, file.getName(), file.open());
                                list.add(postFile);
                            }
                        }
                        
                        files = list.toArray(new HttpClientPostFile[list.size()]);
                    }
                    catch(Exception ex)
                    {
                        for(HttpClientPostFile postFile : list)
                        {
                            postFile._is.close();
                        }
                        throw ex;
                    }
                }
            }
            else
                throw new Exception("unsupport url type : " + url.getClass().getName());
                
            byte[] ret;
            if("GET".equalsIgnoreCase(method))
                ret = _httpClient.getHttpBytes(sUrl, params, heads, encode, notify);
            else if("POST".equalsIgnoreCase(method))
            {
                if(sBody != null)
                    ret = _httpClient.postHttpBytes(sUrl, sBody, heads, encode, notify);
                else
                    ret = _httpClient.postHttpBytes(sUrl, params, heads, encode, notify);
            }
            else if("FILE".equalsIgnoreCase(method))
                ret = _httpClient.postStreamHttp(sUrl, params, heads, encode, files);
            else
                throw new Exception("unsupport method : " + method);
        
            return ret;
        }
        finally
        {
            Context.exit();
        }
    }
    
    protected String[] convNativeObjecToStringArray(NativeObject nvParams)
    {
        if(nvParams != null)
        {
            List<String> list = new ArrayList<String>();
            for(Entry<Object, Object> entry : nvParams.entrySet())
            {
                String key = (String)SMTStatic.unwrapObject(entry.getKey());
                Object value = SMTStatic.unwrapObject(entry.getValue());
                if(value instanceof NativeArray)
                {
                    NativeArray arr = (NativeArray)value;
                    for(int i = 0; i < arr.size(); i ++)
                    {
                        list.add(key);
                        list.add(arr.get(i).toString());
                    }
                }
                else
                {
                    list.add(key);
                    list.add(value.toString());
                }
            }
            return list.toArray(new String[list.size()]);
        }
        
        return null;
    }
}