Created
December 3, 2014 01:19
-
-
Save ryanwarsaw/dfd286312d4c307f0e84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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