You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.5 KiB
42 lines
1.5 KiB
package network;
|
|
|
|
import java.io.InputStream;
|
|
import java.net.URL;
|
|
import java.net.URLConnection;
|
|
import java.net.URLEncoder;
|
|
import java.io.IOException;
|
|
import java.io.UnsupportedEncodingException;
|
|
import network.exceptions.*;
|
|
|
|
//Ref: https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
|
|
public class Net {
|
|
public static String urlStringBuilder(String url, String... paras) throws ParaMismatchException {
|
|
String urlString = url;
|
|
String charset = "UTF-8";
|
|
if ((paras.length % 2) != 0) {
|
|
throw new ParaMismatchException("Except even paras, but have " + paras.length);
|
|
}
|
|
if (paras.length != 0) {
|
|
urlString += "?";
|
|
try {
|
|
for (int i = 0; i < paras.length - 3; i = i + 2) {
|
|
urlString += paras[i] + "=" + URLEncoder.encode(paras[i + 1], charset) + "&";
|
|
}
|
|
urlString += paras[paras.length - 2] + "=" + URLEncoder.encode(paras[paras.length - 1], charset);
|
|
} catch (UnsupportedEncodingException e) {
|
|
System.out.println("Error during encoding url: Unsupported encoding");
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
return urlString;
|
|
}
|
|
|
|
public static InputStream urlToInputStream(String url) throws IOException {
|
|
try {
|
|
return (new URL(url).openStream());
|
|
} catch (IOException e) {
|
|
throw e;
|
|
}
|
|
}
|
|
}
|