Created
November 1, 2013 02:26
-
-
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.
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 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