美文网首页
http请求

http请求

作者: 海货 | 来源:发表于2018-06-27 20:12 被阅读0次

    ajax原生

    @Injectable()
    export class HttpService {
        constructor() {
        }
        public get(url: string, paramObj: any, page?: any) {
            var def = $.Deferred();
            var lang = "zh";
            if (page) {
                paramObj.pageNo = page.pageNo;
                paramObj.pageSize = page.pageSize
            }
            $.ajax({
                url: AppConfig.getMainUrl() + '/' + url,
                type: 'get', //GET
                async: true,    //或false,是否异步
                data: paramObj,
                timeout: 30000,    //超时时间
                dataType: 'json',    //返回的数据格式:json/xml/html/script/jsonp/text
                beforeSend: (xhr) => {
                    xhr.setRequestHeader('_uuid','1234567890');
                    xhr.setRequestHeader('accept-language', lang);
                },
                success: function (data) {
                    def.resolve(data);
                },
                error: (xhr) => {
                    def.resolve(this.handleError(xhr.status))
                },
                complete: function () {
                    // console.log('结束')
                }
            })
            return def.promise();
        }
    
        public get2(url: string, paramObj: any, page?: any) {
            var def = $.Deferred();
            var lang ='zh';
            $.ajax({
                url: AppConfig.getMainUrl() + '/' + url,
                type: 'get', //GET
                async: true,    //或false,是否异步
                data: paramObj,
                timeout: 30000,    //超时时间
                dataType: 'json',    //返回的数据格式:json/xml/html/script/jsonp/text
                beforeSend: (xhr) => {
                    // xhr.setRequestHeader('_uuid', '987654321');
                    xhr.setRequestHeader('accept-language', lang);
                },
                success: function (data) {
                    def.resolve(data);
                },
                error: (xhr) => {
                    def.resolve(this.handleError(xhr.status))
                },
                complete: function () {
                    // console.log('结束')
                }
            })
            return def.promise();
        }
    
        public post(url: string, paramObj: any) {
            var def = $.Deferred();
            var lang = 'zh';
            $.ajax({
                url: AppConfig.getMainUrl() + '/' + url,
                type: 'post', //GET
                async: true,    //或false,是否异步
                data: paramObj,
                timeout: 30000,    //超时时间
                dataType: 'json',    //返回的数据格式:json/xml/html/script/jsonp/text
                beforeSend: (xhr) => {
                    xhr.setRequestHeader('_uuid', '8765432');
                    xhr.setRequestHeader('accept-language', lang);
                },
                success: function (data) {
                    def.resolve(data);
                },
                error: (xhr) => {
                    def.resolve(this.handleError(xhr.status))
                },
                complete: function () {
                    // console.log('结束')
                }
            })
            return def.promise();
        }
    
        public loading_lbank() {
            var loading = this.loadingCtrl.create({
                spinner: 'crescent',
                cssClass: 'lbank_loading',
                showBackdrop: true,
                dismissOnPageChange: true,
                content: '',
                duration: 8000
            });
            return loading;
        }
    
        private handleError(status: Response | any) {
            let msg = '请求失败';
            if (status == 0) {
                msg = '请检查网络';
                // this.lbankDataProvider.setUuId('');
                // this.lbankDataProvider.setIsLogin(false);
            }
            if (status == 400) {
                msg = '请求无效';
            }
            if (status == 404) {
                msg = '请求资源不存在';
            }
            if (status == 401) {
                this.lbankDataProvider.setUuId('');
                this.lbankDataProvider.setIsLogin(false);
                msg = '请重新登录';
            }
            return { success: false, msg: msg };
        }
    }
    

    angular

    
    
    import {Http, Response, Headers, RequestOptions} from '@angular/http';
    import { Injectable } from '@angular/core';
    import { PopServeProvider } from '../pop-serve/pop-serve'
    import { Buffer } from 'buffer';
    // import { AuthHttp, AuthConfig } from 'angular2-jwt';
    
    import { LoadingController, Loading } from 'ionic-angular';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/toPromise';
    
    
    /*
      Generated class for the HttpServeProvider provider.
    
      See https://angular.io/guide/dependency-injection for more info on providers
      and Angular DI.
    */
    
    
    @Injectable()
    export class HttpServeProvider {
      public loadingIsOpen = false;
      public loading:any;
      constructor(public http: Http,
                  public popserve:PopServeProvider,
                  public loadingCtrl: LoadingController) {
        // console.log('Hello HttpServeProvider Provider');
      }
    
    
    
        /**
         * 统一调用此方法显示loading
         * @param content 显示的内容
         */
        showLoading(content: string = ''): void {
            if (!this.loadingIsOpen) {
            this.loadingIsOpen = true;
            this.loading = this.loadingCtrl.create({
                content: content
            });
            this.loading.present();
            setTimeout(() => { //最长显示10秒
                this.loadingIsOpen && this.loading.dismiss();
                this.loadingIsOpen = false;
            }, 10000);
            }
        };
    
    
        /**
         * 关闭loading
         */
        hideLoading(): void {
            this.loadingIsOpen && this.loading.dismiss();
            this.loadingIsOpen = false;
        };
    
    
    
        /**
         * get方式请求
         * @param {string} url     //url
         * @param paramObj      //json对象 如:{name:'大见',age:'23'}
         * @return {Promise<never | {}>}
         */
        get(url:string, paramObj:any = {},content:any = null,showLoad: boolean = null) {
          if(showLoad){
            this.showLoading(content);//调用loading方法显示加载状态
          }
    
          let timestamp = Math.floor(new Date().getTime() / 1000 - 1420070400).toString();    //获取当前时间 减 2015年1月1日的 时间戳
          let headers = new Headers({'timestamp': timestamp});
          let options = new RequestOptions({headers: headers});
          return this.http.get(url + this.toQueryString(paramObj),options)
              .toPromise()
              .then((res)=>{
                let body = res.json();
                this.hideLoading();//有数据返回的时候调用关闭loading的方法
                return body || {};
              })
              .catch((error)=>{
                let errMsg:string;
                if (error instanceof Response) {
                    const body = error.json() || '';
                    const err = body.error || JSON.stringify(body);
                    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
                } else {
                    errMsg = error.message ? error.message : error.toString();
                }
                console.error(errMsg);
                this.hideLoading();//有数据返回的时候调用关闭loading的方法
                return Promise.reject(errMsg);
              })
        }
    
        /**
         * post方式请求
         * @param {string} url
         * @param body       //如:paramObj:{name:'大见',age:'23'}
         * @param {string} contentType      //post请求的编码方式  application/x-www-form-urlencoded  multipart/form-data   application/json   text/xml
         * @return {Promise<never | {}>}
         */
    
        post(url:string, body:any = {},content:any = null,showLoad: boolean = null,token:string='',contentType:string="application/json;charset=UTF-8") {
    
          if(showLoad){ //在请求数据的地方传入是否需要显示loading
            this.showLoading(content);//调用loading方法显示加载状态
          }
    
          let headers;
          if(token==''){
            headers = new Headers({'Content-Type':contentType});
          }else if(token!=''){
            headers = new Headers({'Content-Type':contentType,'Authorization':'bearer '+token});
          }
          let options = new RequestOptions({headers: headers});
          return this.http.post(url, JSON.stringify(body),options)
              .toPromise()
              .then((res)=>{
                let body = res.json();
                this.hideLoading();//有数据返回的时候调用关闭loading的方法
                return body || {};
              })
              .catch((error)=>{
                let errMsg:string;
                if (error instanceof Response) {
                    const body = error.json() || '';
                    const err = body.error || JSON.stringify(body);
                    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
                } else {
                    errMsg = error.message ? error.message : error.toString();
                }
                console.error(errMsg);
                this.hideLoading();//有数据返回的时候调用关闭loading的方法
                return Promise.reject(errMsg);
              }); 
        }
    
    
        /**
         * get请求参数处理 
         *  对于get方法来说,都是把数据串联在请求的url后面作为参数,如果url中出现中文或其它特殊字符的话,很常见的一个乱码问题就要出现了
         *  url拼接完成后,浏览器会对url进行URL encode,然后发送给服务器,URL encode的过程就是把部分url做为字符,按照某种编码方式(如:utf-8,gbk等)编码成二进制的字节码
         * 不同的浏览器有不同的做法,中文版的浏览器一般会默认的使用GBK,通过设置浏览器也可以使用UTF-8,可能不同的用户就有不同的浏览器设置,也就造成不同的编码方式,
         * 所以通常做法都是先把url里面的中文或特殊字符用 javascript做URL encode,然后再拼接url提交数据,也就是替浏览器做了URL encode,好处就是网站可以统一get方法提交数据的编码方式。
         * @param obj 参数对象
         * @return {string} 参数字符串
         * @example
         *  声明: var obj= {'name':'大见',age:23};
         *  调用: toQueryString(obj);
         *  返回: "?name=%E5%B0%8F%E5%86%9B&age=23"
         */
    
          private toQueryString(obj) {
            let ret = [];
            for (let key in obj) {
                key = encodeURIComponent(key);
                let values = obj[key];
                if (values && values.constructor == Array) {//数组
                    let queryValues = [];
                    for (let i = 0, len = values.length, value; i < len; i++) {
                        value = values[i];
                        queryValues.push(this.toQueryPair(key, value));
                    }
                    ret = ret.concat(queryValues);
                } else { //字符串
                    ret.push(this.toQueryPair(key, values));
                }
            }
            return '?' + ret.join('&');
        }
    
        /**
         *  post请求参数处理
         * @param obj
         * @return {string}
         *  声明: var obj= {'name':'大见',age:23};
         *  调用: toQueryString(obj);
         *  返回: "name=%E5%B0%8F%E5%86%9B&age=23"
         */
        
        private toBodyString(obj) {
            let ret = [];
            for (let key in obj) {
                key = encodeURIComponent(key);
                // key = key;
                let values = obj[key];
                if (values && values.constructor == Array) {//数组
                    let queryValues = [];
                    for (let i = 0, len = values.length, value; i < len; i++) {
                        value = values[i];
                        queryValues.push(this.toQueryPair(key, value));
                    }
                    ret = ret.concat(queryValues);
                } else { //字符串
                    ret.push(this.toQueryPair(key, values));
                }
            }
            return ret.join('&');
        }
    
        private toQueryPair(key, value) {
          if (typeof value == 'undefined') {
              return key;
          }
          return key + '=' + encodeURIComponent(value === null ? '' : String(value));
          // return key + '=' +(value === null ? '' : String(value));
        }
    
        private toSignPair(key, value) {
            return key + '=' + (value === null ? '' : String(value));
        }
    
    }
    
    

    rxjs

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpInterceptor, HttpRequest, HttpEvent, HttpHandler, HttpResponse } from '@angular/common/http';
    
    import { Observable } from 'rxjs';
    import { catchError, tap, finalize, retry } from 'rxjs/operators';
    
    /**
     *
     * http模块
     * @export
     * @class HttpProvider
     */
    @Injectable()
    export class HttpProvider {
      httpOptions: any = {
        headers: new HttpHeaders({})
      };
    
      constructor(public http: HttpClient) { }
    
      /**
       * GET请求
       * @param {string} url
       * @returns {Observable<any>}
       * @memberof HttpProvider
       */
      public get(url: string): Observable<any> {
        return this.http.get(url, this.httpOptions)
          .timeout(30000)
          .pipe(
            retry(3),
            catchError(this.handleError)
          );
      }
    
    
      /**
       * POST请求
       * @param {string} url
       * @param {*} params
       * @returns {Observable<any>}
       * @memberof HttpProvider
       */
      public post(url: string, params: any): Observable<any> {
        return this.http.post(url, params, this.httpOptions)
          .timeout(30000)
          .pipe(
            retry(3),
            catchError(this.handleError)
          );
      }
    
      /**
       * 请求失败
       * @private
       * @param {Response} error
       * @returns {Observable<any>}
       * @memberof HttpProvider
       */
      private handleError(error: Response): Observable<any> {
        //在这里可以提供一些失败的提示
        return Observable.throw(error);
      }
    }
    
    
    @Injectable()
    export class ReqInterceptor implements HttpInterceptor {
    
      constructor() { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpEvent<any>> {
        console.log('Request1........', req)
    
        //请求前的处理
        req = req.clone({
          setHeaders: {
            '_uuid': '23821406e57f9015f425c42c8bb1db2163534e614115bd4660772f8483b680ed785d21789bf5e82c9c369bde7cebbf1964b0db80e6f8df5f4202da77b3e5430de6fed4963a67955c7eac09edd4016135',
            'accept-language': 'zh-CN'
          },
          setParams: {
            'source': '2',
            'deviceNumber': '1233132'
          }
        });
    
        console.log('Request2........', req)
    
        return next.handle(req);
      }
    }
    
    
    @Injectable()
    export class ResInterceptor implements HttpInterceptor {
      constructor() { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('4567890')
    
        return next.handle(req).map(event => {
    
          if (event instanceof HttpResponse) {
            console.log('response......', event)
          }
          return event;
        }
        )
      }
    }
    
    @Injectable()
    export class LogInterceptor implements HttpInterceptor {
      constructor() { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('4567890')
    
        return next.handle(req).pipe(
          tap(
            event => console.log('11111111', event),
            error => console.log('2222222', error)
          ),
          finalize(
            () => {
              console.log('3333333')
            }
          )
        );
      }
    
      // intercept(req: HttpRequest<any>, next: HttpHandler) {
      //   const started = Date.now();
      //   let ok: string;
    
      //   // extend server response observable with logging
      //   return next.handle(req)
      //     .pipe(
      //       tap(
      //         // Succeeds when there is a response; ignore other events
      //         event => ok = event instanceof HttpResponse ? 'succeeded' : '',
      //         // Operation failed; error is an HttpErrorResponse
      //         error => ok = 'failed'
      //       ),
      //       // Log when response observable either completes or errors
      //       finalize(() => {
      //         const elapsed = Date.now() - started;
      //         const msg = `${req.method} "${req.urlWithParams}"
      //            ${ok} in ${elapsed} ms.`;
      //         this.messenger.add(msg);
      //       })
      //     );
      // }
    }
    
    
    

    相关文章

      网友评论

          本文标题:http请求

          本文链接:https://www.haomeiwen.com/subject/ntviyftx.html