-
Notifications
You must be signed in to change notification settings - Fork 23
/
HTTPSource.java
60 lines (51 loc) · 1.57 KB
/
HTTPSource.java
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
package in.xiandan.mmrc.datasource;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* http数据源
* @author dengyuhan
* created 2019-06-28 16:45
*/
public class HTTPSource implements DataSource<String> {
private String mUrl;
private Map<String, String> mHeaders;
public HTTPSource(@NonNull String url, @Nullable Map<String, String> headers) {
this.mUrl = url;
this.mHeaders = headers;
}
@NonNull
@Override
public String source() {
return mUrl;
}
@NonNull
public Map<String, String> getHeaders() {
return mHeaders == null ? new HashMap<>() : mHeaders;
}
@NonNull
@Override
public InputStream toStream() throws IOException {
if (TextUtils.isEmpty(mUrl)) {
throw new UnknownHostException(mUrl);
}
final URL url = new URL(mUrl);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (mHeaders != null) {
final Set<Map.Entry<String, String>> entries = mHeaders.entrySet();
for (Map.Entry<String, String> entry : entries) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
return connection.getInputStream();
}
}