Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package me.ryanw.launch.me.ryanw.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class RESTful {
public final static RESTful INSTANCE = new RESTful();
private RESTful() {}
public static String httpGet(String urlString) throws IOException {
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() != 200) {
throw new IOException(connection.getResponseMessage());
}
BufferedReader read = new BufferedReader (new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = read.readLine()) != null) {
stringBuilder.append(line);
}
read.close();
connection.disconnect();
return stringBuilder.toString();
}
public static String httpPost(String urlString, String[] name, String[] value) throws IOException {
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Content-Type", "application/x/www/form/urlencoded");
OutputStream out = connection.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < name.length; i++) {
writer.write(name[i]);
writer.write("=");
writer.write(URLEncoder.encode(name[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (connection.getResponseCode() != 200) {
throw new IOException(connection.getResponseMessage());
}
BufferedReader read = new BufferedReader (new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line = read.readLine()) != null) {
stringBuilder.append(line);
}
read.close();
connection.disconnect();
return stringBuilder.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.