Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created February 11, 2018 17:28
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 jigewxy/64f76fb5c7ab5507bdbe524168cf4b04 to your computer and use it in GitHub Desktop.
Save jigewxy/64f76fb5c7ab5507bdbe524168cf4b04 to your computer and use it in GitHub Desktop.
http request sample - java
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