Created
February 11, 2018 17:28
-
-
Save jigewxy/64f76fb5c7ab5507bdbe524168cf4b04 to your computer and use it in GitHub Desktop.
http request sample - java
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
import java.net.*; | |
import java.io.*; | |
public class DemoHttpRequest{ | |
public static void main(String[] args) { | |
try{ | |
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}"; | |
String cliff = "{\"name\":\"cliff\"}"; | |
URL url = new URL("http://localhost:3000/post"); | |
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); | |
conn.setRequestMethod("POST"); | |
conn.setDoInput(true); | |
conn.setDoOutput(true); | |
conn.setRequestProperty("Accept", "application/json"); | |
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); | |
DataOutputStream out = new DataOutputStream(conn.getOutputStream()); | |
out.writeBytes(cliff); | |
out.flush(); | |
out.close(); | |
//character stream | |
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
FileWriter fw = new FileWriter("./result.txt"); | |
String inputLine; | |
StringBuffer content = new StringBuffer(); | |
while ((inputLine = in.readLine()) != null) { | |
content.append(inputLine); | |
} | |
in.close(); | |
conn.disconnect(); | |
fw.write(content.toString()); | |
System.out.println(content); | |
fw.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment