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
| package ohos_app_cangjie_entry.api import ohos.net.http.* import ohos.base.* import std.collection.* import ohos_app_cangjie_entry.bean.* import ohos.hilog.* import std.time.* import std.sync.* import ohos.state_manage.* let mtx = ReentrantMutex()
public class APiRequest { let baseURL = 'https://www.wanandroid.com/' let httpRequest = createHttp(); var responseResult = ResponseResult() var isRequestFinish = AtomicBool(false)
public func request():ResponseResult{ let option = HttpRequestOptions( method: RequestMethod.GET, // 可选,默认为http.RequestMethod.GET expectDataType: HttpDataType.STRING, // 可选,指定返回数据的类型 usingCache: true, // 可选,默认为true priority: 1, // 可选,默认为1 // 开发者根据自身业务需要添加header字段 header: HashMap<String, String>([("content-type", "application/json")]), readTimeout: 60000, // 可选,默认为60000ms connectTimeout: 60000, // 可选,默认为60000ms usingProtocol: HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 usingProxy: UsingProxy.USE_DEFAULT, //可选,默认不使用网络代理,自API 10开始支持该属性 )
try { // Hilog.info(0, "test", "resp===: 开始请求") //https://wanandroid.com/harmony/index/json //https://wanandroid.com/popular/column/json httpRequest.request('https://wanandroid.com/popular/column/json', {err, resp => if (let Some(e) <- err) { Hilog.error(0, "test","exception: ${e.message}") this.responseResult.errorCode = 400 this.responseResult.errorMsg = e.message this.responseResult.data = "" } if (let Some(r) <- resp) { Hilog.info(0, "test", "resp===: ${r.result}") //r.responseCode this.responseResult.errorCode = 200 this.responseResult.errorMsg = "请求成功" this.responseResult.data = r.result.toString()
} else { Hilog.error(0, "test", "response is none") this.responseResult.errorCode = 400 this.responseResult.errorMsg = "response is none" this.responseResult.data = "" }}, options: option) sleep(Duration.second * 1) //Hilog.info(0, "test", "resp===: 结束请求") return responseResult }catch (exception:Exception) { this.responseResult.errorCode = 400 this.responseResult.errorMsg = "${exception.message}" this.responseResult.data = "出错了" return responseResult }finally { //sleep(Duration.second * 1) //return responseResult } } }
|