Created
September 19, 2014 12:16
-
-
Save cstrap/76d739c1169ef738dae5 to your computer and use it in GitHub Desktop.
Example of REST client with POST data
This file contains hidden or 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
import java.io.BufferedReader; | |
import java.io.DataOutputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.nio.charset.Charset; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class RESTClient { | |
public static String callUrl(String urlToCall) { | |
StringBuilder sb = new StringBuilder(); | |
HttpURLConnection urlConn = null; | |
InputStreamReader in = null; | |
try { | |
URL url = new URL(urlToCall); | |
urlConn = (HttpURLConnection) url.openConnection(); | |
urlConn.setRequestProperty("Content-Type", "application/json; charset=utf8"); | |
urlConn.setRequestProperty("Accept", "application/json"); | |
urlConn.setRequestMethod("POST"); | |
urlConn.setDoOutput(true); | |
DataOutputStream wr = new DataOutputStream(urlConn.getOutputStream()); | |
wr.writeBytes("{}"); | |
wr.flush(); | |
wr.close(); | |
if (urlConn != null) { | |
urlConn.setReadTimeout(60 * 1000); | |
} | |
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK | |
&& urlConn != null | |
&& urlConn.getInputStream() != null) { | |
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); | |
BufferedReader bufferedReader = new BufferedReader(in); | |
if (bufferedReader != null) { | |
int cp; | |
while ((cp = bufferedReader.read()) != -1) { | |
sb.append((char) cp); | |
} | |
bufferedReader.close(); | |
} | |
} | |
in.close(); | |
} catch (Exception e) { | |
throw new RuntimeException("Exception while calling URL:" + urlToCall, e); | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment