Skip to content

Instantly share code, notes, and snippets.

@woosungchu
Last active October 11, 2017 15:04
Show Gist options
  • Save woosungchu/d1e3e4dc2ef5cea5a7a20fe87b6b6371 to your computer and use it in GitHub Desktop.
Save woosungchu/d1e3e4dc2ef5cea5a7a20fe87b6b6371 to your computer and use it in GitHub Desktop.
JavaFetcher.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
//https://code.google.com/archive/p/json-simple
public class Fetcher {
private static JSONParser jsonParser = new JSONParser();
public static void main(String[] args) {
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://httpbin.org";
String response = sendPostRequest(requestUrl+"/get","GET","");
String response2 = sendPostRequest(requestUrl+"/post","POST",payload);
parse(response);
parse(response2);
}
public static String sendPostRequest(String requestUrl, String method, String payload) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
if(!"".equals(payload)) {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
}
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
private static void parse(String json) {
JSONObject obj = null;
try {
obj = (JSONObject) jsonParser.parse(json);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment