Java http connection

|

자바에서 url connection을 사용해보자.

1. GET 방식

// HTTP GET request
public void sendingGetRequest(String urlString) throws Exception {

	URL url = new URL(urlString);
	HttpURLConnection con = (HttpURLConnection) url.openConnection();

	con.setRequestMethod("GET");

	con.setRequestProperty("User-Agent", "Mozilla/5.0");

	int responseCode = con.getResponseCode();
	System.out.println("Sending get request : " + url);
	System.out.println("Response code : " + responseCode);

	BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream()));
	String output;
	StringBuffer response = new StringBuffer();

	while ((output = in.readLine()) != null) {
		response.append(output);
	}
	in.close();

	System.out.println(response.toString());
};

2. POST 방식 1 - json string parameter

 // HTTP Post request
 public String sendPostString(String urlString, String jsonData) throws Exception {

	URL obj = new URL(urlString);
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();

	con.setRequestMethod("POST");
	con.setRequestProperty("User-Agent", "Mozilla/5.0");
	con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
	con.setRequestProperty("Content-Type","application/json");

	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.writeBytes(jsonData);
	wr.flush();
	wr.close();

	//int responseCode = con.getResponseCode();

	BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream())
	);
	String output;
	StringBuffer response = new StringBuffer();

	while ((output = in.readLine()) != null) {
		response.append(output);
	}
	in.close();

	return response.toString();
};

3. POST 방식 2 - Name, value parameter

// HTTP Post request
public String sendPostNameValue(String urlString, List<NameValuePair> nameValuePairs) throws Exception {

	HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(urlString);

    // add header
    post.setHeader("User-Agent", "Mozilla/5.0");

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
    	result.append(line);
    }

    return result.toString();
};