1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.quicksearchbox.util
17 
18 import java.io.IOException
19 
20 /** An interface that can issue HTTP GET / POST requests with timeouts. */
21 interface HttpHelper {
getnull22   @Throws(IOException::class, HttpException::class) operator fun get(request: GetRequest?): String?
23 
24   @Throws(IOException::class, HttpException::class)
25   operator fun get(url: String?, requestHeaders: MutableMap<String, String>?): String?
26 
27   @Throws(IOException::class, HttpException::class) fun post(request: PostRequest?): String?
28 
29   @Throws(IOException::class, HttpException::class)
30   fun post(url: String?, requestHeaders: MutableMap<String, String>?, content: String?): String?
31   fun setConnectTimeout(timeoutMillis: Int)
32   fun setReadTimeout(timeoutMillis: Int)
33   open class GetRequest {
34     /** Gets the request URI. */
35     /** Sets the request URI. */
36     var url: String? = null
37 
38     /**
39      * Gets the request headers.
40      *
41      * @return The response headers. May return `null` if no headers are set.
42      */
43     var headers: MutableMap<String, String>? = null
44       private set
45 
46     /** Creates a new request. */
47     constructor()
48 
49     /**
50      * Creates a new request.
51      *
52      * @param url Request URI.
53      */
54     constructor(url: String?) {
55       this.url = url
56     }
57 
58     /**
59      * Sets a request header.
60      *
61      * @param name Header name.
62      * @param value Header value.
63      */
64     fun setHeader(name: String, value: String) {
65       if (headers == null) {
66         headers = mutableMapOf()
67       }
68       headers?.put(name, value)
69     }
70   }
71 
72   class PostRequest : GetRequest {
73     var content: String? = null
74 
75     constructor()
76     constructor(url: String?) : super(url)
77   }
78 
79   /** A HTTP exception. */
80   class HttpException(
81     /** Gets the HTTP response status code. */
82     val statusCode: Int,
83     /** Gets the HTTP response reason phrase. */
84     val reasonPhrase: String
85   ) : IOException("$statusCode $reasonPhrase")
86 
87   /** An interface for URL rewriting. */
88   interface UrlRewriter {
rewritenull89     fun rewrite(url: String): String
90   }
91 }
92