반응형

아파치의 httpcomponenet를 활용하여 http 통신 테스트를 해본다.

 

그러기 위해서는 pom.xml에 아래를 추가한다.

 

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.4</version>
</dependency>

그뒤 패키지를 만들고 그 안에 void 자바파일을 하나 만든다.

 

패키지명: com.test.httpConnection01

 

파일명: HttpConnectionTest01.java

package com.test.httpConnection01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpConnectionTest01 {
	
    private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "http://www.google.com";    
 
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);

        //agent 정보 설정
        httpGet.addHeader("User-Agent", USER_AGENT);
        
      //get 요청
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("::GET Response Status::");
        
        //response의 status 코드 출력
        System.out.println("status code: "+httpResponse.getStatusLine().getStatusCode());
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));
 
        String inputLine;
        StringBuffer response = new StringBuffer();
 
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        
        reader.close();
 
        //Print result
        System.out.println(response.toString());
        httpClient.close();
    }

}

 

그리고 위 메소드를 실행할 파일을 하나 만든다.

 

파일명: HttpConnectionTextExec.java

package com.test.httpConnection01;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

public class HttpConnectionTextExec {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			//예제1 connection 테스트
			HttpConnectionTest01.sendGet();
			

			//System.out.println("==============비트코인 가격  json 시작=================");
			//예제2 비트코인가격 Json
			//HttpConnectionTest02.sendGet();
			
			
		
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}

}

 

코드를 완성 한 후 실행하면 아래와 같은 결과를 얻는다.

::GET Response Status::
status code: 200
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"

 

그런데 json을 받아오는 경우가 많으므로 json 예제파일을 하나 더 만들어보자.

 

파일명: HttpConnectionTest02

package com.test.httpConnection01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpConnectionTest02 {

	
	
	private static final String USER_AGENT = "Mozila/5.0";

	//비트코인 가격 json API 주소
    private static final String GET_URL = "https://api.blockchain.com/v3/exchange/tickers/"+
    "BTC-USD";


    
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);
        
        //agent 정보 설정
        httpGet.addHeader("User-Agent", USER_AGENT);
        httpGet.addHeader("Content-type", "application/json");
        
        //get 요청
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        

       System.out.println("status code: "+httpResponse.getStatusLine().getStatusCode());
        String json = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        
        
        
        System.out.println(json);
        
        httpClient.close();


    }
}

 

그리고 실행 파일에서 예제1에 주석을 걸고, 예제2 비트코인 가격 부분 주석을 푼다.

package com.test.httpConnection01;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

public class HttpConnectionTextExec {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			//예제1 connection 테스트
			//HttpConnectionTest01.sendGet();
			

			System.out.println("==============비트코인 가격  json 시작=================");
			//예제2 비트코인 가격
			HttpConnectionTest02.sendGet();
			
			
		
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}

}

 

그러면 결과값은 아래와 같다.

==============비트코인 가격  json 시작=================
status code: 200
{"symbol":"BTC-USD","price_24h":35775.7,"volume_24h":63.66743294,"last_trade_price":35717.4}

 

더나아가서 비트코인 가격만 나타나려고 하면 json으로 그 값을 저장하는 변수를 추가해줘야한다.

 

pom.xml에 아래와 같이 GSON 메이븐을 추가해준다. (json-simple이 아닌 gson이다.)

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.1</version>
</dependency>

 

그뒤 비트코인 가격 클래스에 json parsing 코드를 넣는다.

package com.test.httpConnection01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class HttpConnectionTest02 {

	
	
	private static final String USER_AGENT = "Mozila/5.0";
/*    private static final String GET_URL = "https://blockchain.info/ko"
            + "/rawblock/0000000000000bae09a7a393a8acd"
            + "ed75aa67e46cb81f7acaa5ad94f9eacd103";*/
    
	//비트코인 가격 json API 주소
    private static final String GET_URL = "https://api.blockchain.com/v3/exchange/tickers/"+
    "BTC-USD";


    
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);
        
        //agent 정보 설정
        httpGet.addHeader("User-Agent", USER_AGENT);
        httpGet.addHeader("Content-type", "application/json");
        
        //get 요청
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        

       System.out.println("status code: "+httpResponse.getStatusLine().getStatusCode());
        String json = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        String sdsd="dsd";
        
        
        System.out.println(json);
        
        //Json parsing 추가
        JsonParser jsonParser= new JsonParser(); //JsonParser를 불러온다.
        JsonObject jsonObj= (JsonObject) jsonParser.parse(json); //json을 오브젝트 형식으로 파싱함
        
        JsonElement last_trade_price = jsonObj.get("last_trade_price");
        
        
        
        
        System.out.println("비트코인 가격: "+last_trade_price);
        
        
        httpClient.close();


    }
}

 

그 뒤 실행 파일에서 실행해보면 결과는 아래와 같다.

==============비트코인 가격  json 시작=================
status code: 200
{"symbol":"BTC-USD","price_24h":35666.0,"volume_24h":62.14906458,"last_trade_price":36196.52}
비트코인 가격: 36196.52

 

 

반응형

+ Recent posts