Skip to content

Instantly share code, notes, and snippets.

@film42
Created November 1, 2013 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save film42/7260192 to your computer and use it in GitHub Desktop.
Save film42/7260192 to your computer and use it in GitHub Desktop.
Here's a little static class that just does a post and get, for a school project.
package servertester.modules;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: film42
* Date: 10/31/13
* Time: 7:52 PM
*/
public class HttpClient {
/**
* Generic HTTP client goodness in one wonderful bundle
*
* @param url
* @param method
* @param request
* @return
* @throws Exception
*/
private static String request(String url, String method, String request) throws Exception {
try {
URL requestURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
// We can generalize, whatever
connection.setDoOutput(true);
connection.setRequestMethod(method);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(request);
outputStreamWriter.close();
return inputStreamToString(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
throw new Exception("Request error");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("Request error");
}
}
public static String get(String url) {
try {
return request(url, "GET", "");
} catch (Exception e) {
return null;
}
}
public static String post(String url, String request) {
try {
return request(url, "POST", request);
} catch (Exception e) {
return null;
}
}
// Copied from server.handlers.common.BaseHandler.java
private static String inputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try { bufferedReader.close(); } catch (IOException e) {
e.printStackTrace(); }
}
return stringBuilder.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment