Skip to content

Instantly share code, notes, and snippets.

@L-Soft
Created December 16, 2019 17:32
Show Gist options
  • Save L-Soft/c969ce722979e430008f53c53bb47af0 to your computer and use it in GitHub Desktop.
Save L-Soft/c969ce722979e430008f53c53bb47af0 to your computer and use it in GitHub Desktop.
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestfulAPI {
public void post (String sURL, String sJSON) {
try {
URL url = new URL(sURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000); // 서버에 연결되는 Timeout 시간 설정
con.setReadTimeout(5000); // InputStream 읽어 오는 Timeout 시간 설정
// con.addRequestProperty("x-api-key", "토크값");
con.setRequestMethod("POST");
//json으로 message를 전달하고자 할 때
con.setRequestProperty("Content-Type", "application/json");
con.setDoInput(true);
con.setDoOutput(true); //POST 데이터를 OutputStream으로 넘겨 주겠다는 설정
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setRequestProperty("Accept", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(sJSON); //json 형식의 message 전달
wr.flush();
StringBuilder sb = new StringBuilder();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK ||
con.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
InputStream is = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[1024];
byte[] byteData = null;
int nLength = 0;
while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
JSONObject responseJSON = new JSONObject(new String(byteData));
System.out.println(responseJSON);
} else {
System.out.println(con.getResponseMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JSONObject object = new JSONObject();
object.put("title", "test");
object.put("body", "test");
RestfulAPI restfulAPI = new RestfulAPI();
restfulAPI.post("http://localhost:3001/memo", object.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment