1- const request = require ( 'request' ) ;
1+ // const request = require('request');
22const QueryString = require ( "querystring" ) ;
3+ const https = require ( 'https' ) ;
4+ const http = require ( 'http' ) ;
5+ const url = require ( 'url' ) ;
36
47/**
58 * @inner
69 */
710class HttpConnection {
8- static doRequest ( method , url , data , callback , opt = { } ) {
9- let req = {
10- method : method ,
11- url : url ,
12- } ;
13- if ( method === "GET" ) {
14- req . url += "?" + QueryString . stringify ( data ) ;
15- } else {
16- req . form = data ;
17- }
18- Object . assign ( req , opt ) ;
19- request ( req , function ( error , response , body ) {
11+ static doRequest ( method , reqUrl , data , callback , opt = { } ) {
12+ // let req = {
13+ // method: method,
14+ // url: reqUrl ,
15+ // }
16+ // data.Signature = 'fk';
17+ // if (method === "GET") {
18+ // req.url += "?" + QueryString.stringify(data);
19+ // } else {
20+ // req.form = data;
21+ // }
22+ // request(req, function (error, response, body) {
2023 /**
2124 * `.request` 的请求回调
2225 * @callback requestCallback
2326 * @param {Error } error 请求错误
2427 * @param {Object } response 请求响应
2528 * @param {String } body API 请求结果
2629 */
30+ // callback(error, response, body);
31+ // })
32+
33+ // node http[s] raw module send request
34+ let httpClient ;
35+ const urlObj = url . parse ( reqUrl ) ;
36+ switch ( urlObj . protocol . toLocaleLowerCase ( ) ) {
37+ case 'https:' :
38+ httpClient = https ;
39+ break ;
40+ case 'http:' :
41+ default :
42+ httpClient = http ;
43+ break ;
44+ }
45+
46+ const httpBody = QueryString . stringify ( data ) ;
47+ opt = opt || { } ;
48+
49+ opt . method = method ;
50+ if ( method === "GET" ) {
51+ reqUrl += "?" + httpBody ;
52+ } else {
53+ opt [ 'headers' ] = opt [ 'headers' ] || { } ;
54+ opt [ 'headers' ] [ 'Content-Type' ] = 'application/json' ;
55+ opt [ 'headers' ] [ 'Content-Length' ] = Buffer . byteLength ( httpBody ) ;
56+ }
2757
28- callback ( error , response , body ) ;
29- } )
58+ const clientObject = httpClient . request ( reqUrl , opt , function ( res ) {
59+ let body = '' ;
60+ res . on ( 'data' , function ( chunk ) {
61+ body += chunk ;
62+ } ) ;
63+ res . on ( 'end' , ( ) => {
64+ callback ( null , res , body ) ;
65+ } )
66+ } ) ;
67+
68+ clientObject . on ( 'error' , function ( e ) {
69+ callback ( e , null , null ) ;
70+ } ) ;
71+
72+ clientObject . write ( httpBody )
73+
74+ clientObject . end ( ) ;
3075 }
3176}
3277module . exports = HttpConnection ;
0 commit comments