下面列出了java.net.http.HttpResponse.BodyHandlers#java.net.URLEncoder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 下载文件名重新编码
*
* @param request 请求对象
* @param fileName 文件名
* @return 编码后的文件名
*/
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains(MSIE)) {
// IE浏览器
filename = URLEncoder.encode(filename, CharsetUtil.UTF_8);
filename = filename.replace("+", " ");
} else if (agent.contains(FIREFOX)) {
// 火狐浏览器
filename = new String(fileName.getBytes(), CharsetUtil.ISO_8859_1);
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, CharsetUtil.UTF_8);
}
return filename;
}
/**
* 接口获取二维码信息
* @return
* @throws UnsupportedEncodingException
*/
public static com.alibaba.fastjson.JSONObject getScanCodeList() throws UnsupportedEncodingException {
PropertiesUtil util = new PropertiesUtil("jeewx.properties");
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("weixinId", util.readProperty("weixinId"));
paramMap.put("channel", util.readProperty("channel"));
paramMap.put("sceneId", util.readProperty("sceneId"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
Date afterDate = new Date(now.getTime() + 60000);
Date beforeDate = new Date(now.getTime() - 120000);
paramMap.put("fromDate", sdf.format(beforeDate));
paramMap.put("endDate", sdf.format(afterDate));
String sign = SignatureUtil.sign(paramMap, util.readProperty("scanRecordKey"));
String h = util.readProperty("validCodeUrl")+"&weixinId="+util.readProperty("weixinId")+"&channel="+util.readProperty("channel")+"&sceneId="+util.readProperty("sceneId")+"&fromDate="+URLEncoder.encode(sdf.format(beforeDate),"utf-8")+"&endDate="+URLEncoder.encode(sdf.format(afterDate),"utf-8")+"&signature="+sign;
com.alibaba.fastjson.JSONObject object = WeiXinHttpUtil.sendGet(h);
return object;
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadVideo(@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) throws Exception {
File videoDir = new File(this.videoDirectory);
if (!videoDir.exists()) {
videoDir.mkdirs();
}
File uploadFile = new File(videoDir.getAbsolutePath(), fileDetail.getFileName());
writeToFile(uploadedInputStream, uploadFile.getAbsolutePath());
Video video = new Video();
video.setPath(String.format("%s/rest/public/videos/%s", this.baseUrl, URLEncoder.encode(fileDetail.getFileName(), "UTF8")));
return Response.OK(video);
}
public static String concatUrl(String url, Map<String, String> data) {
if (data == null) {
return url;
}
try {
StringBuilder sb = new StringBuilder();
for (Entry<String, String> entry : data.entrySet()) {
sb.append("&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8"));
}
if (sb.length() < 1) {
return url;
}
String prefix = sb.substring(1).toString();
if (url.indexOf("?") < 1) {
url += "?";
}
return url + prefix;
} catch (Exception ex) {
LOGGER.warn("{}", ex);
}
return url;
}
@Override
public String getWechatAuthorizeUrl(String app, HttpServletRequest request, String toUrl)
throws UnsupportedEncodingException {
log.info("引导到授权页:{},{}", app, toUrl);
WechatInfo wechatInfo = getWechatInfo(app);
// 网关域名(外网)加路由到用户系统的规则 https://xxx.xxx.xxx/api-u
String domain = wechatConfig.getDomain();
StringBuilder redirectUri = new StringBuilder(domain + "/wechat/" + app + "/back");
if (StringUtils.isNoneBlank(toUrl)) {
toUrl = URLEncoder.encode(toUrl, "utf-8");
redirectUri.append("?toUrl=").append(toUrl);
}
String redirect_uri = URLEncoder.encode(redirectUri.toString(), "utf-8");
// 生成一个随机串,微信再跳回来的时候,会原封不动给我们带过来,到时候做一下校验
String state = UUID.randomUUID().toString();
request.getSession().setAttribute(STATE_WECHAT, state);
return String.format(WECHAT_AUTHORIZE_URL, wechatInfo.getAppid(), redirect_uri, state);
}
@SuppressWarnings("deprecation")
public static String DBRequest(String request) throws IOException {
URL url = new URL("http://localhost:3306/" + URLEncoder.encode(request));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()),"UTF-8"));
String out = "";
String out1;
while ((out1 = br.readLine()) != null) {
out += out1;
}
conn.disconnect();
return out;
}
/**
* 保存cookies
* @param response
* @param name
* @param value
* @param time
* @return HttpServletResponse
*/
public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value,int expiry) {
// new一个Cookie对象,键值对为参数
Cookie cookie = new Cookie(name, value);
// tomcat下多应用共享
cookie.setPath("/");
cookie.setHttpOnly(true);
cookie.setMaxAge(expiry);
// 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码
try {
URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 将Cookie添加到Response中,使之生效
response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie
return response;
}
public boolean checkProcessorExist(HttpServletRequest request) {
try {
String payload = "{\"a\":\"1\",\"b\":\"test\",\"c\":\"10\"}";
String condition = "\"c<100\"";
String url = new StringBuffer(this.getProcessorUrl()).append(ConstantProperties.PROCESSOR_CHECK_WHERE_CONDITION)
.append(ConstantProperties.QUESTION_MARK).append("payload=").append(URLEncoder.encode(payload, "UTF-8"))
.append("&condition=").append(URLEncoder.encode(condition, "UTF-8"))
.toString();
CloseableHttpResponse closeResponse = commonService.getCloseResponse(request, url);
int statusCode = closeResponse.getStatusLine().getStatusCode();
return 200 == statusCode;
} catch (Exception e) {
return false;
}
}
private boolean isExternalEndpointAvailable() throws IOException {
HttpClient httpClient = new DefaultHttpClient();
String url = "http://semantic.eea.europa.eu/sparql?query=";
String query = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"
+ "PREFIX cr:<http://cr.eionet.europa.eu/ontologies/contreg.rdf#>\n"
+ "SELECT * WHERE { ?bookmark a cr:SparqlBookmark;rdfs:label ?label} LIMIT 50";
url = url + URLEncoder.encode(query, "UTF-8");
HttpGet httpGet = new HttpGet(url);
httpClient.getParams().setParameter("http.socket.timeout", 300000);
httpGet.setHeader("Accept", "text/xml");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return true;
}
return false;
}
@Override
public final String asString() {
return new UncheckedText(
new JoinedText(
"&",
new Mapped<>(
input -> String.format(
"%s=%s", input.key(),
URLEncoder.encode(
input.value(),
"UTF-8"
)
),
new Mapped<>(
in -> new KvpOf(in.key().substring(2), in.value()),
new Filtered<>(
input -> input.key().startsWith("f."),
this.dict
)
)
)
)
).asString();
}
/**
* Serialize column family to data block encoding map to configuration.
* Invoked while configuring the MR job for incremental load.
*
* @param table to read the properties from
* @param conf to persist serialized values into
* @throws IOException
* on failure to read column family descriptors
*/
@VisibleForTesting
static void configureDataBlockEncoding(HTableDescriptor tableDescriptor, Configuration conf)
throws UnsupportedEncodingException {
if (tableDescriptor == null) {
// could happen with mock table instance
return;
}
StringBuilder dataBlockEncodingConfigValue = new StringBuilder();
Collection<HColumnDescriptor> families = tableDescriptor.getFamilies();
int i = 0;
for (HColumnDescriptor familyDescriptor : families) {
if (i++ > 0) {
dataBlockEncodingConfigValue.append('&');
}
dataBlockEncodingConfigValue.append(URLEncoder.encode(familyDescriptor.getNameAsString(), "UTF-8"));
dataBlockEncodingConfigValue.append('=');
DataBlockEncoding encoding = familyDescriptor.getDataBlockEncoding();
if (encoding == null) {
encoding = DataBlockEncoding.NONE;
}
dataBlockEncodingConfigValue.append(URLEncoder.encode(encoding.toString(), "UTF-8"));
}
conf.set(DATABLOCK_ENCODING_FAMILIES_CONF_KEY, dataBlockEncodingConfigValue.toString());
}
public static Map<String, Object> dataCX(Analyzer analyzer, String string) throws UnsupportedEncodingException {
System.out.println(string);
Map<String, String> pos = analyzer.getPosCnToCn();
List<String> sets = analyzer.parserString(string);
Iterator<String> iterator = sets.iterator();
String cx = "";
while(iterator.hasNext()) {
String token = iterator.next();
if(pos.containsKey(token)) {
cx += token + "/"+pos.get(token)+" ";
}
}
Map<String, Object> outputMap = new HashMap<>();
outputMap.put(URLEncoder.encode("cx","UTF-8"), URLEncoder.encode(cx,"UTF-8"));
return outputMap;
}
public void getMatchingModels()throws Exception{
String portType = "output";
// String protobufJsonString = "[{\"role\":\"repeated\",\"tag\":\"1\",\"type\":\"string\"},{\"role\":\"repeated\",\"tag\":\"2\",\"type\":\"string\"}]";
List<MessageargumentList> messageargumentListList= new ArrayList<>();
MessageargumentList messageargumentList = new MessageargumentList();
messageargumentList.setRole("repeated");
messageargumentList.setTag("1");
messageargumentList.setType("string");
MessageargumentList messageargumentList2 = new MessageargumentList();
messageargumentList2.setRole("repeated");
messageargumentList2.setTag("2");
messageargumentList2.setType("string");
messageargumentListList.add(messageargumentList);
messageargumentListList.add(messageargumentList2);
String pp = new Gson().toJson(messageargumentListList);
// System.out.println("****************** "+ pp);
// JsonArray jsonArray = new JsonArray();
// jsonArray.add(pp);
String r = URLEncoder.encode(pp, "UTF-8");
// System.out.println("******************after encode "+ r);
restSolutionMockMvc.perform(get("/api/solutions/matchingModels?&userId="+DEFAULT_AUTHOR_LOGIN+"&portType="
+configurationProperties.getMatchingInputPortType()+"&protobufJsonString="+r))
.andExpect(status().isOk());
}
private void findGuild(String name, boolean byPlayerName) {
updateStatus(I18n.translate("server.hypixel.loading"));
if (byPlayerName) {
The5zigMod.getMojangAPIManager().resolveUUID(name, new ExceptionCallback<String>() {
@Override
public void call(String uuid, Throwable throwable) {
findGuild("byUuid=" + uuid);
}
});
} else {
try {
findGuild("byName=" + URLEncoder.encode(name, "UTF-8"));
} catch (UnsupportedEncodingException e) {
updateStatus(e.getMessage());
}
}
}
public String urlEncode(final String input) {
/*
* **************************************************
* IMPORTANT IMPORTANT IMPORTANT IMPORTANT
* **************************************************
*
* DO NOT REMOVE METHOD OR CHANGE SIGNATURE!!!
*/
try {
return URLEncoder.encode(input, "UTF-8");
} catch (final Exception e) {
return "";
}
}
@Override
public void configure(HttpSecurity http) throws Exception {
String logoutUrl = env.getProperty("endSessionEndpoint") + "?post_logout_redirect_uri=" +
URLEncoder.encode(env.getProperty("homePage"), "UTF-8");
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.logout()
.deleteCookies()
.invalidateHttpSession(true)
.logoutSuccessUrl(logoutUrl);
}
@Test
void invalidUrl() {
assertThat(assertThrows(
IllegalArgumentException.class,
() -> ConnectionFactories.get("r2dbcs:mysql://[email protected]:3306?" +
"unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8"))).getMessage())
.contains("sslMode");
for (SslMode mode : SslMode.values()) {
if (mode.startSsl()) {
assertThat(assertThrows(
IllegalArgumentException.class,
() -> ConnectionFactories.get("r2dbc:mysql://[email protected]:3306?" +
"unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8") +
"&sslMode=" + mode.name().toLowerCase())).getMessage())
.contains("sslMode");
}
}
}
/**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param cookieMaxage cookie生效的最大秒数
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
System.out.println(domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
public String build() {
UrlBuilder ub = new UrlBuilder(EhUrl.getFavoritesUrl());
if (isValidFavCat(mFavCat)) {
ub.addQuery("favcat", Integer.toString(mFavCat));
} else if (mFavCat == FAV_CAT_ALL) {
ub.addQuery("favcat", "all");
}
if (!TextUtils.isEmpty(mKeyword)) {
try {
ub.addQuery("f_search", URLEncoder.encode(mKeyword, "UTF-8"));
// Name
ub.addQuery("sn", "on");
// Tags
ub.addQuery("st", "on");
// Note
ub.addQuery("sf", "on");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Can't URLEncoder.encode " + mKeyword);
}
}
if (mIndex > 0) {
ub.addQuery("page", Integer.toString(mIndex));
}
return ub.build();
}
@Test
void validUrl() throws UnsupportedEncodingException {
assertThat(ConnectionFactories.get("r2dbc:mysql://[email protected]:3306")).isExactlyInstanceOf(MySqlConnectionFactory.class);
assertThat(ConnectionFactories.get("r2dbcs:mysql://[email protected]:3306")).isExactlyInstanceOf(MySqlConnectionFactory.class);
assertThat(ConnectionFactories.get("r2dbc:mysql://[email protected]:3306?unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8")))
.isExactlyInstanceOf(MySqlConnectionFactory.class);
assertThat(ConnectionFactories.get("r2dbcs:mysql://[email protected]:3306?" +
"unixSocket=" + URLEncoder.encode("/path/to/mysql.sock", "UTF-8") +
"&sslMode=disabled")).isNotNull();
assertThat(ConnectionFactories.get(
"r2dbcs:mysql://root:[email protected]:3306/r2dbc?" +
"zeroDate=use_round&" +
"sslMode=verify_identity&" +
"serverPreparing=true" +
String.format("tlsVersion=%s&", URLEncoder.encode("TLSv1.1,TLSv1.2,TLSv1.3", "UTF-8")) +
String.format("sslCa=%s&", URLEncoder.encode("/path/to/ca.pem", "UTF-8")) +
String.format("sslKey=%s&", URLEncoder.encode("/path/to/client-key.pem", "UTF-8")) +
String.format("sslCert=%s&", URLEncoder.encode("/path/to/client-cert.pem", "UTF-8")) +
"sslKeyPassword=ssl123456"
)).isExactlyInstanceOf(MySqlConnectionFactory.class);
}
@Override
public ResponseDTO<String> getFileUrl(String path) {
OSSConfig ossConfig = systemConfigService.selectByKey2Obj(SystemConfigEnum.Key.QI_NIU_OSS.name(), OSSConfig.class);
try {
if (! ossConfig.toString().equals(accessConfig)) {
//accessKeyId 发生变动自动重新创建新的UploadManager
ossClient = new UploadManager(new Configuration());
token = Auth.create(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()).
uploadToken(ossConfig.getBucketName());
accessConfig = ossConfig.toString();
}
String encodedFileName = URLEncoder.encode(path, "utf-8");
String domainOfBucket = ossConfig.getEndpoint();
String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
String accessKey = ossConfig.getAccessKeyId();
String secretKey = ossConfig.getAccessKeySecret();
Auth auth = Auth.create(accessKey, secretKey);
//1小时,可以自定义链接过期时间
long expireInSeconds = 3600;
String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
return ResponseDTO.succData(finalUrl);
} catch (Exception e) {
log.error("QINIU getFileUrl ERROR : {}", e);
}
return ResponseDTO.wrap(FileResponseCodeConst.URL_ERROR);
}
public StringsExpressionProcessor(ILocationProvider locationProvider)
{
super(List.of(
new UnaryExpressionProcessor("trim", StringUtils::trim),
new UnaryExpressionProcessor("toLowerCase", StringUtils::lowerCase),
new UnaryExpressionProcessor("toUpperCase", StringUtils::upperCase),
new UnaryExpressionProcessor("capitalize", StringUtils::capitalize),
new UnaryExpressionProcessor("uncapitalize", StringUtils::uncapitalize),
new UnaryExpressionProcessor("generate", input -> generate(locationProvider.getLocale(), input)),
new UnaryExpressionProcessor("generateLocalized", generateLocalized()),
new UnaryExpressionProcessor("encodeUrl", input -> URLEncoder.encode(input, UTF_8)),
new UnaryExpressionProcessor("loadResource", ResourceUtils::loadResource),
new UnaryExpressionProcessor("resourceToBase64", input -> Base64.getEncoder()
.encodeToString(ResourceUtils.loadResourceAsByteArray(input))),
new UnaryExpressionProcessor("decodeFromBase64", input -> new String(Base64.getDecoder()
.decode(input.getBytes(UTF_8)), UTF_8)),
new UnaryExpressionProcessor("encodeToBase64", input -> new String(Base64.getEncoder()
.encode(input.getBytes(UTF_8)), UTF_8)),
new UnaryExpressionProcessor("anyOf", StringsExpressionProcessor::anyOf)
));
}
private FullHttpResponse login(String email, String password, ChannelHandlerContext ctx) throws Exception {
FullHttpRequest fakeLogin = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
fakeLogin.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
String params = new StringBuilder("password=")
.append(URLEncoder.encode(password, CharsetUtil.UTF_8.name()))
.append("&")
.append("user=")
.append(URLEncoder.encode(email, CharsetUtil.UTF_8.name()))
.toString();
ByteBuf buffer = Unpooled.copiedBuffer(params, CharsetUtil.UTF_8);
fakeLogin.headers().add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes());
fakeLogin.content().clear().writeBytes(buffer);
return authenticator.authenticateRequest(ctx.channel(), fakeLogin);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
/**
* 活动二维码下载 (通用方法)
* @param url :二维码网址
*/
@RequestMapping(value = "downMatrix", method ={RequestMethod.GET,RequestMethod.POST})
public void downMatrix(@RequestParam(required = true, value = "qrCodeName") String qrCodeName,@RequestParam(required = true, value = "url") String url, HttpServletResponse response, HttpServletRequest request) throws Exception {
String text = url;
int width = 500; // 二维码图片宽度
int height = 500; // 二维码图片高度
String format = "jpg";// 二维码的图片格式
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, width, height, hints);
// 获取文件名
String fileName = "";
if(qrCodeName!=null)
{
fileName = qrCodeName+".jpg";
}else{
fileName = "活动二维码.jpg";
}
// 制定浏览器头
// 在下载的时候这里是英文是没有问题的
// 如果图片名称是中文需要设置转码
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
OutputStream out = response.getOutputStream();;
try {
// 读取文件
MatrixToImageWriter.writeToStream(bitMatrix, format, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
protected static String encode(String s) throws IllegalArgumentException {
try {
return URLEncoder.encode(s, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
}
private static String URLEndoder(String str){
try {
return URLEncoder.encode(str,"utf-8");
} catch (UnsupportedEncodingException e) {
LOGGER.warn("endoe failed:",e);
return str;
}
}
/**
* 付款通知
*
* @throws IOException
*/
public static void confirmPay(String mobile, String code) throws IOException {
mobile = URLEncoder.encode(mobile, YunPianUrlParam.ENCODING);
YunPianParam yunPianParam = new YunPianParam();
yunPianParam.setTpl_id("2416230");
yunPianParam.setMobile(mobile);
yunPianParam.setCode(code);
getYZM(yunPianParam);
}
/**
* 编码字符串
* @param text 字符串
* @return
*/
public static String encodeURL(String text){
try {
return URLEncoder.encode(text, CommonConfig.UNIFY_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
protected String doInBackground(Void... voids) {
HashMap<String, String> headers = new HashMap<>();
headers.put("Client-ID", "jzkbprff40iqj646a697cyrvl0zt2m6");
int idx;
if ((idx = videoId.indexOf('&')) > 0) {
videoId = videoId.substring(0, idx);
}
String streamCode = downloadUrlContent(this, String.format(Locale.US, "https://api.twitch.tv/kraken/streams/%s?stream_type=all", videoId), headers, false);
if (isCancelled()) {
return null;
}
try {
JSONObject obj = new JSONObject(streamCode);
JSONObject stream = obj.getJSONObject("stream");
String accessTokenCode = downloadUrlContent(this, String.format(Locale.US, "https://api.twitch.tv/api/channels/%s/access_token", videoId), headers, false);
JSONObject accessToken = new JSONObject(accessTokenCode);
String sig = URLEncoder.encode(accessToken.getString("sig"), "UTF-8");
String token = URLEncoder.encode(accessToken.getString("token"), "UTF-8");
URLEncoder.encode("https://youtube.googleapis.com/v/" + videoId, "UTF-8");
String params = "allow_source=true&" +
"allow_audio_only=true&" +
"allow_spectre=true&" +
"player=twitchweb&" +
"segment_preference=4&" +
"p=" + (int) (Math.random() * 10000000) + "&" +
"sig=" + sig + "&" +
"token=" + token;
String m3uUrl = String.format(Locale.US, "https://usher.ttvnw.net/api/channel/hls/%s.m3u8?%s", videoId, params);
results[0] = m3uUrl;
results[1] = "hls";
} catch (Exception e) {
FileLog.e(e);
}
return isCancelled() ? null : results[0];
}