Skip to content

Commit 339f1d9

Browse files
authored
Merge pull request #349 from wb9688/okhttp
Use OkHttp for tests like in NewPipe
2 parents 970bc7f + a65e46e commit 339f1d9

2 files changed

Lines changed: 54 additions & 79 deletions

File tree

extractor/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ dependencies {
88
implementation 'org.nibor.autolink:autolink:0.10.0'
99

1010
testImplementation 'junit:junit:4.13'
11+
testImplementation "com.squareup.okhttp3:okhttp:3.12.11"
1112
}

extractor/src/test/java/org/schabi/newpipe/DownloaderTestImpl.java

Lines changed: 53 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -4,123 +4,97 @@
44
import org.schabi.newpipe.extractor.downloader.Request;
55
import org.schabi.newpipe.extractor.downloader.Response;
66
import org.schabi.newpipe.extractor.exceptions.ReCaptchaException;
7-
import org.schabi.newpipe.extractor.localization.Localization;
87

9-
import javax.annotation.Nonnull;
10-
import javax.annotation.Nullable;
11-
import javax.net.ssl.HttpsURLConnection;
128
import java.io.IOException;
13-
import java.io.InputStream;
14-
import java.io.InputStreamReader;
15-
import java.io.OutputStream;
16-
import java.net.URL;
17-
import java.net.URLConnection;
189
import java.util.List;
1910
import java.util.Map;
11+
import java.util.concurrent.TimeUnit;
12+
13+
import javax.annotation.Nonnull;
14+
import javax.annotation.Nullable;
2015

21-
public class DownloaderTestImpl extends Downloader {
16+
import okhttp3.OkHttpClient;
17+
import okhttp3.RequestBody;
18+
import okhttp3.ResponseBody;
2219

23-
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0";
24-
private static final String DEFAULT_HTTP_ACCEPT_LANGUAGE = "en";
20+
public final class DownloaderTestImpl extends Downloader {
21+
private static final String USER_AGENT
22+
= "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0";
23+
private static DownloaderTestImpl instance;
24+
private OkHttpClient client;
2525

26-
private static DownloaderTestImpl instance = null;
26+
private DownloaderTestImpl(final OkHttpClient.Builder builder) {
27+
this.client = builder.readTimeout(30, TimeUnit.SECONDS).build();
28+
}
2729

28-
private DownloaderTestImpl() {
30+
/**
31+
* It's recommended to call exactly once in the entire lifetime of the application.
32+
*
33+
* @param builder if null, default builder will be used
34+
* @return a new instance of {@link DownloaderTestImpl}
35+
*/
36+
public static DownloaderTestImpl init(@Nullable final OkHttpClient.Builder builder) {
37+
instance = new DownloaderTestImpl(
38+
builder != null ? builder : new OkHttpClient.Builder());
39+
return instance;
2940
}
3041

3142
public static DownloaderTestImpl getInstance() {
3243
if (instance == null) {
33-
synchronized (DownloaderTestImpl.class) {
34-
if (instance == null) {
35-
instance = new DownloaderTestImpl();
36-
}
37-
}
44+
init(null);
3845
}
3946
return instance;
4047
}
4148

42-
private void setDefaultHeaders(URLConnection connection) {
43-
connection.setRequestProperty("User-Agent", USER_AGENT);
44-
connection.setRequestProperty("Accept-Language", DEFAULT_HTTP_ACCEPT_LANGUAGE);
45-
}
46-
4749
@Override
48-
public Response execute(@Nonnull Request request) throws IOException, ReCaptchaException {
50+
public Response execute(@Nonnull final Request request)
51+
throws IOException, ReCaptchaException {
4952
final String httpMethod = request.httpMethod();
5053
final String url = request.url();
5154
final Map<String, List<String>> headers = request.headers();
52-
@Nullable final byte[] dataToSend = request.dataToSend();
53-
@Nullable final Localization localization = request.localization();
54-
55-
final HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
55+
final byte[] dataToSend = request.dataToSend();
5656

57-
connection.setConnectTimeout(30 * 1000); // 30s
58-
connection.setReadTimeout(30 * 1000); // 30s
59-
connection.setRequestMethod(httpMethod);
57+
RequestBody requestBody = null;
58+
if (dataToSend != null) {
59+
requestBody = RequestBody.create(null, dataToSend);
60+
}
6061

61-
setDefaultHeaders(connection);
62+
final okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder()
63+
.method(httpMethod, requestBody).url(url)
64+
.addHeader("User-Agent", USER_AGENT);
6265

6366
for (Map.Entry<String, List<String>> pair : headers.entrySet()) {
6467
final String headerName = pair.getKey();
6568
final List<String> headerValueList = pair.getValue();
6669

6770
if (headerValueList.size() > 1) {
68-
connection.setRequestProperty(headerName, null);
71+
requestBuilder.removeHeader(headerName);
6972
for (String headerValue : headerValueList) {
70-
connection.addRequestProperty(headerName, headerValue);
73+
requestBuilder.addHeader(headerName, headerValue);
7174
}
7275
} else if (headerValueList.size() == 1) {
73-
connection.setRequestProperty(headerName, headerValueList.get(0));
76+
requestBuilder.header(headerName, headerValueList.get(0));
7477
}
75-
}
7678

77-
@Nullable OutputStream outputStream = null;
78-
@Nullable InputStreamReader input = null;
79-
try {
80-
if (dataToSend != null && dataToSend.length > 0) {
81-
connection.setDoOutput(true);
82-
connection.setRequestProperty("Content-Length", dataToSend.length + "");
83-
outputStream = connection.getOutputStream();
84-
outputStream.write(dataToSend);
85-
}
79+
}
8680

87-
final InputStream inputStream = connection.getInputStream();
88-
final StringBuilder response = new StringBuilder();
81+
final okhttp3.Response response = client.newCall(requestBuilder.build()).execute();
8982

90-
// Not passing any charset for decoding here... something to keep in mind.
91-
input = new InputStreamReader(inputStream);
83+
if (response.code() == 429) {
84+
response.close();
9285

93-
int readCount;
94-
char[] buffer = new char[32 * 1024];
95-
while ((readCount = input.read(buffer)) != -1) {
96-
response.append(buffer, 0, readCount);
97-
}
86+
throw new ReCaptchaException("reCaptcha Challenge requested", url);
87+
}
9888

99-
final int responseCode = connection.getResponseCode();
100-
final String responseMessage = connection.getResponseMessage();
101-
final Map<String, List<String>> responseHeaders = connection.getHeaderFields();
102-
final String latestUrl = connection.getURL().toString();
103-
104-
return new Response(responseCode, responseMessage, responseHeaders, response.toString(), latestUrl);
105-
} catch (Exception e) {
106-
final int responseCode = connection.getResponseCode();
107-
108-
/*
109-
* HTTP 429 == Too Many Request
110-
* Receive from Youtube.com = ReCaptcha challenge request
111-
* See : https://github.com/rg3/youtube-dl/issues/5138
112-
*/
113-
if (responseCode == 429) {
114-
throw new ReCaptchaException("reCaptcha Challenge requested", url);
115-
} else if (responseCode != -1) {
116-
final String latestUrl = connection.getURL().toString();
117-
return new Response(responseCode, connection.getResponseMessage(), connection.getHeaderFields(), null, latestUrl);
118-
}
89+
final ResponseBody body = response.body();
90+
String responseBodyToReturn = null;
11991

120-
throw new IOException("Error occurred while fetching the content", e);
121-
} finally {
122-
if (outputStream != null) outputStream.close();
123-
if (input != null) input.close();
92+
if (body != null) {
93+
responseBodyToReturn = body.string();
12494
}
95+
96+
final String latestUrl = response.request().url().toString();
97+
return new Response(response.code(), response.message(), response.headers().toMultimap(),
98+
responseBodyToReturn, latestUrl);
12599
}
126100
}

0 commit comments

Comments
 (0)