[JAVA_Back-End]

[JAVA] Network 본문

Programming/JAVA

[JAVA] Network

너굴위 2023. 9. 19. 16:41
728x90
반응형

내일

* 개인 프로젝트.. 

금요일

- SQL 

퀴즈

SQL 캡처화면


[Lambda]

자바스크립트: 화살표 함수

MainEx01.java - 인터페이스 사용하기
package pack1;


public class MainEx01 {


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

//익명 내부클래스
new MyFunctionalInter() {

@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("메소드 호출");
}
}.method();


//또 다른 방법
MyFunctionalInter f = new MyFunctionalInter() {

@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("메소드 호출");
}
};

f.method();
}


}

 

MainEx02.java - Lambda함수 사용하여 호출하기
package pack1;


public class MainEx02 {


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


MyFunctionalInter f;

//Lambda함수로 호출하기
/* f=() -> {
System.out.println("methon()호출");
}; */

f= () -> System.out.println("methon()호출"); //한줄로 표현 가능
f.method();

}


}

 

MyFunctionalInter.java - 추상메소드가 있는 함수형 인터페이스
package pack1;


//함수형 인터페이스
public interface MyFunctionalInter {

void method(); //추상메소드
//1. 구현 -> method 오버라이딩..
//2. 익명 내부클래스로 선언 후 사용
}

MainEx01.java - 람다함수를 이용해서 메서드 호출
package pack2;


public class MainEx01 {


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


MyFunctionalInter f = ()-> System.out.println("methon()호출");
f.method1();
}
}

 

MyFunctionalInter.java - @FunctionalInterface 어노테이션을 추가한 함수형 인터페이스
package pack2;


//함수형 인터페이스는 반드시 한 개의 메서드만 존재해야함
@FunctionalInterface //함수형 인터페이스가 가능한지에 대해 평가해주는 어노테이션
public interface MyFunctionalInter {


void method1();
//void method2();
}

Ex14_1   - 반환타입을 지정하여 메서드 출력
package pack3;


public class Ex14_1 {
static void execute(MyFunction f) {
f.run();
}

//중요
static MyFunction getMyFunction() { //반환 타입이 MyFunction인 메서드
MyFunction f = ()-> System.out.println("f3.run()");
return f;
}






public static void main(String[] args) {
//람다식으로 MyFunction의 run()을 구현
MyFunction f1 =()-> System.out.println("f1.run()");

MyFunction f2 = new MyFunction() { //익명클래스로 run()을 구현

@Override
public void run() { //public을 반드시 붙여야 함
// TODO Auto-generated method stub
System.out.println("f2.run()");
}
};

MyFunction f3 = getMyFunction();

f1.run();
f2.run();
f3.run();

execute(f1);
execute(()->System.out.println("run()"));

}
}

 

MyFunction - 메서드가 포함된 interface
package pack3;


@FunctionalInterface
public interface MyFunction {


void run();
}

자바언어 네트워크 구성(장비) - 통신(데이터의 교환)

 

Lan                    - 랜카드

    유선

    무선(wifi)

============================컴vs컴

무선통신(전화)망 - 5g / 4g LTE  - 카드

블루투스   - 동글

USB   - 동글

============================컴vs장비(IOT)

widi

serial

 

Lan(Local Area Network)

       인트라넷 - 사내망

       인터넷     - 사외망

 

데이터 흐름

프로그램 -> os -> 네트워크 카드 -> 인터넷 -> 네트워크 카드 -> os -> 프로그램

 

인터넷 상의 위치에 대한 규약

ip(Internet Protocol)  => 도메인

            IPv4  0~255.0~255.0~255.0~255

            IPv6  여섯개의 문자로 구성

 

            공인 IP - 인터넷 업체에서 제공(유료)

            비공인IP  - 공유기에서 생성되는 IP 

                              192.168.xxx.xxx

            루프백    - 네트워크 카드 체크용

                             127.0.0.1

 

port   - 프로그램에 제공되는 주소 ( 프로그램 당 1개 이상 가지고 있음)

         - 프로토콜: 전송규약

           0 ~ 1023: Well-Known port

           49152 ~ : 사용자 포트

 

 

URL

https://search.daum.net/search?DA=YZR&o=&orgq=cntjr&q=%EC%B6%94%EC%84%9D&spacing=2&sq=&sug=&sugo=&t__nil_searchbox=btn&w=tot

-> 특정 부분만 추출

 

=> 웹 서버의 클라이언트

    <- html 문서를 읽어올 수 있음

*브라우저

   1. html 문서 읽어오기

   2. html 문서 렌더링

InetAddressEx01.java - 도메인의 ip확인하기
import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressEx01 {

public static void main(String[] args) {   //도메인의 IP확인할 수 있도록 하는 클래스 
try {

//ip <-> domain
InetAddress inetAddress = InetAddress.getByName("www.daum.net");

System.out.println(inetAddress.getHostName());
System.out.println(inetAddress.getHostAddress());

InetAddress[] inetAddresses
=InetAddress.getAllByName("www.naver.com");

for(InetAddress address : inetAddresses) {
System.out.println(address.getHostAddress());
}

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ex16_2.java - url정보 가져오기
import java.net.URL;


public class Ex16_2 {


public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
URL url = new URL("https://search.daum.net/search?DA=YZR&o=&orgq=cntjr&q=%EC%B6%94%EC%84%9D&spacing=2&sq=&sug=&sugo=&t__nil_searchbox=btn&w=tot");

System.out.println("url.getAuthority():"+url.getAuthority());
System.out.println("url.getContent():"+url.getContent());
System.out.println("url.getDefaultPort():"+url.getDefaultPort());
System.out.println("url.getPort():"+url.getPort());
System.out.println("url.getFile():"+url.getFile());
System.out.println("url.getHost():"+url.getHost());
System.out.println("url.getPath():"+url.getPath());
System.out.println("url.getProtocol():"+url.getProtocol());
System.out.println("url.getQuery():"+url.getQuery());
System.out.println("url.getRef():"+url.getRef());
System.out.println("url.getUserInfo():"+url.getUserInfo());
System.out.println("url.toExternalForm():"+url.toExternalForm());
System.out.println("url.toURI():"+url.toURI());
}


}

결과

 

 

URLConnectionEx02.java - Http접속에 대한 상세한 접속 관련 정보 얻기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class URLConnectionEx02 {


public static void main(String[] args) {
BufferedReader br = null;

try {
//URLConnection으로 연결
//URLConnection conn = new URL("https://news.daum.net").openConnection();

//Http접속에 대한 상세한 접속 관련 정보 얻을 수 있음
HttpURLConnection conn =(HttpURLConnection) new URL("https://news.daum.net").openConnection();
br=new BufferedReader(new InputStreamReader(conn.getInputStream())); //연결 내용을 버퍼로 받아와서 읽어들임

String line = null;
while((line=br.readLine())!=null) {
System.out.println(line);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(br!=null)try {br.close();}catch(IOException e) {}
}


}


}

-> 결과는 동일

 

URLEx03.java - 웹 페이지의 태그 가져오기
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;


public class URLEx03 {


public static void main(String[] args) {
// TODO Auto-generated method stub
InputStream is = null;

try {

URL url = new URL("https://m.daum.net");
is = url.openStream();

int data =0;
while((data =is.read())!=-1) {
System.out.print((char)data);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
}finally {
if(is !=null) try {is.close();}catch(IOException e) {};
}
}


}

 

URLConnectionEx03.java - 웹 페이지의 이미지 가져오기(원격)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class URLConnectionEx03 {


//웹 페이지의 이미지를 가져올 수 있다. (원격으로)
public static void main(String[] args) {
// TODO Auto-generated method stub
//https://t1.daumcdn.net/daumtop_chanel/op/20200723055344399.png
BufferedInputStream bis = null; //이미지를 버퍼 스트림으로 읽고 출력한다
BufferedOutputStream bos =null;


try {
URLConnection conn = new URL("https://t1.daumcdn.net/daumtop_chanel/op/20200723055344399.png").openConnection();
bis = new BufferedInputStream(conn.getInputStream());
bos= new BufferedOutputStream(new FileOutputStream("./daum.png"));

int data =0;
while((data=bis.read())!=-1) {
bos.write(data);
}
System.out.println("전송완료");
} catch (MalformedURLException e) {
System.out.println("에러: "+e.getMessage());
} catch (FileNotFoundException e) {
System.out.println("에러: "+e.getMessage());
} catch (IOException e) {
System.out.println("에러: "+e.getMessage());
}finally {
if(bos!=null)try {bos.close();}catch(IOException e) {}
if(bis!=null)try {bis.close();}catch(IOException e) {}
}
}

}
ImageViewerEx01.java - 저장한 이미지 불러오기
import java.awt.EventQueue;


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JTextField;


public class ImageViewerEx01 extends JFrame {


private JPanel contentPane;
private JButton btn2;
private JButton btn1;
private JTextField txtHttp;


/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ImageViewerEx01 frame = new ImageViewerEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


/**
* Create the frame.
*/
public ImageViewerEx01() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 800);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));


setContentPane(contentPane);
contentPane.setLayout(null);

btn1 = new JButton("이미지 저장");
btn1.addMouseListener(new MouseAdapter() {
//이미지 저장 불러오기
@Override
public void mouseClicked(MouseEvent e) {
//btn2.setIcon(new ImageIcon("C:\\Java\\java-workspace\\NetworkEx01\\daum.png")); //버튼을 클릭했을 때 이미지를 보여줄 수 있도록 함
try {
//이미지의 URL경로를 통해서 이미지를 불러올 수 있다
btn2.setIcon(new ImageIcon(new URL("https://t1.daumcdn.net/daumtop_chanel/op/20200723055344399.png")));
} catch (MalformedURLException e1) {
System.out.println("에러: "+e1.getMessage());
}

}
});
btn1.setBounds(442, 42, 130, 23);
contentPane.add(btn1);

JPanel panel2 = new JPanel();
panel2.setBounds(12, 75, 560, 655);
contentPane.add(panel2);
panel2.setLayout(new BorderLayout(0, 0));

btn2 = new JButton("");
//btn2.setIcon(new ImageIcon("C:\\Java\\java-workspace\\NetworkEx01\\daum.png"));
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel2.add(btn2, BorderLayout.CENTER);

txtHttp = new JTextField();
txtHttp.setText("http://");
txtHttp.setBounds(12, 43, 418, 21);
contentPane.add(txtHttp);
txtHttp.setColumns(10);
}
}

 

URLEx02.java - URL의 특정 내용 가져오기 (태그와 클래스를 통해)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class URLEx02 {

public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br=null;
//InputStreamReader isr =null;
//InputStream is = null;

try {

URL url = new URL("https://news.daum.net");
//URL url = new URL("https://m.daum.net");
br=new BufferedReader(new InputStreamReader(url.openStream()));
//isr =new InputStreamReader( url.openStream());

//int data =0;
/*while((data =isr.read())!=-1) {
Syste m.out.print((char)data); 
}*/
String line = null;
boolean flag =false;

while(( line=br.readLine())!=null) {

if(line.trim().contains("class=\"link_txt\"")) {
flag=true;
}
 
             
if(line.contains("</a>")){
flag=false;
}

if(flag) {   //특정문자포함된 열을 건너뛰기
if(line.indexOf("<a href")<0)
System.out.println(line.trim());
}

}


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
}finally {
if(br !=null) try {br.close();}catch(IOException e) {};
}
}

}

결과물

 

 


 

jsoup.jar파일 ClassPath에 추가하여 사용

JSoupEx01.java - JSoup jar파일 추가한 후 html태그 출력하기
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class JSoupEx01 {


public static void main(String[] args) {
String html = "<html>"
+"<head>"
+"<title>First parse</title>"
+"</head>"
+ "<body>"
+"<p>Parsed HTML into a doc.1</p>"
+"<p>Parsed HTML into a doc.2</p>"
+ "</body>"
+ "</html>";

//JSoup < = python beautifulsoup을 통해 만든것이다.

Document doc = Jsoup.parse(html);
System.out.println(doc.toString());

Elements titles = doc.getElementsByTag("title");
System.out.println(titles);
System.out.println(titles.text());

// p teg의 내용을 쉽게 가져올 수 있다.

Elements pTags = doc.getElementsByTag("p");
System.out.println(pTags);
System.out.println(pTags.size());

for(int i=0; i<pTags.size();i++) {
Element pTag= pTags.get(i);
System.out.println(pTag.tagName());
System.out.println(pTag.text());
}



}


}

결과

 

 

 

JSoupEx02.java - 클래스의 이름을 통해 내용 가져오기
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JSoupEx02 {

public static void main(String[] args) {
String html = "<html>"
+"<head>"
+"<title>First parse</title>"
+"</head>"
+ "<body>"
+"<p id='i1'  class='c1'>Parsed HTML into a doc.1</p>"
+"<p id='i2'  class='c2'>Parsed HTML into a doc.2</p>"
+"<p id='i3'  class='c1'>Parsed HTML into a doc.3</p>"
+"<p id='i4'  class='c2'>Parsed HTML into a doc.4</p>"
+ "</body>"
+ "</html>";

//JSoup  < = python beautifulsoup을 통해 만든것이다.

Document doc = Jsoup.parse(html);


//doc.getElementById();        //ID만 단수형(Element) 나머지는 복수형(Elements)으로 적는다 

//doc.getElementsByTag();
//doc.getElementsByClass();
//doc.getElementsByAttribute();

//i1에 대한 pTag를 가져온다
//Element pTag = doc.getElementById("i1");
//System.out.println(pTag);

//c1에 대한 pTag를 가져온다
Elements pTag = doc.getElementsByClass("c1");
System.out.println(pTag);

}

}

결과

 

URLEx04.java - URL의 특정 내용 가져오기 (JSoup을 통해)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class URLEx04 {

public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br=null;
//InputStreamReader isr =null;
//InputStream is = null;

try {

URL url = new URL("https://news.daum.net");
//URL url = new URL("https://m.daum.net");
br=new BufferedReader(new InputStreamReader(url.openStream()));

String line = null;
boolean flag =false;
StringBuilder sbHtml=new StringBuilder();
while(( line=br.readLine())!=null) {
sbHtml.append(line.trim());
}

Document doc = Jsoup.parse(sbHtml.toString());

Elements lists = doc.getElementsByAttributeValue("data-tiara-layer","article_main");
for(Element list:lists) {
System.out.println(list.text());
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
}finally {
if(br !=null) try {br.close();}catch(IOException e) {};
}
}

}

웹사이트 정보

- 크롤링

- 스크래핑

html분석용 라이브러리-

Jsoup

https://jsoup.org/

 

html

  - 문자열

  - 객체 - DOM

 

*크롤링 - html안에 있는 데이터

* 정식 데이터 제공  -> 현업데이터

   OpenAPI

   1. xml

   2. json

   3. library

  공공데이터 포털   https://www.data.go.kr/index.do

 https://www.kofic.or.kr

https://www.kobis.or.kr/kobisopenapi/homepg/main/main.do

 

xml         - String, JSoup, Jackson, Sax ...

extensible markup language

태그와 속성을 통해서 데이터를 정의(html과 비슷)

 

주소록

홍길동, 010-1000-1111, 20, 서울시

 

=> 

<name>홍길동</name>

<phone>010-1000-1111</phone>

<age>20</age>

<region>서울시</region>

 

 

JSON(Javascript Object Notation) - String, 별도 라이브러리

{} - Object

[] - 배열

 

OpenAPIEx01.java - 영화번호, 순위, 영화명을 차례로 출력하기 (Jsoup이용)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class OpenAPIEx01 {


public static void main(String[] args) {

//xml
//http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.xml?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230916


// TODO Auto-generated method stub
BufferedReader br=null;
StringBuilder sbXml=new StringBuilder();

try {

URL url = new URL("http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.xml?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230916");
br=new BufferedReader(new InputStreamReader(url.openStream()));

String line = null;

while(( line=br.readLine())!=null) {
sbXml.append(line.trim());
}

System.out.println(sbXml);
Document doc = Jsoup.parse(sbXml.toString());

Elements nmTags = doc.getElementsByTag("movieNm");
Elements nmrnums= doc.getElementsByTag("rnum");
Elements nmranks= doc.getElementsByTag("rank");
//System.out.println(nmTags);
for(int i=0;i<nmrnums.size();i++) { //영화 번호, 영화 순위, 영화명 순서로 나열
Element nmTag = nmTags.get(i);
Element nmrnum =nmrnums.get(i);
Element nmrank =nmranks.get(i);

System.out.print(nmrnum.text()+"\t");
System.out.print(nmrank.text()+"\t");
System.out.print(nmTag.text()+"\t");

System.out.println();
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
}finally {
if(br !=null) try {br.close();}catch(IOException e) {};
}
}

}

 

결과

 

OpenAPIEx02.java - 박스오피스 제목만 출력하기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class OpenAPIEx02 {

public static void main(String[] args) {

//json
// http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchWeeklyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230916 

BufferedReader br=null;
StringBuilder sbJson=new StringBuilder();

try {

URL url = new URL(" http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchWeeklyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230916 ");
br=new BufferedReader(new InputStreamReader(url.openStream()));

String line = br.readLine();

line= line.replaceAll(",", "\n");

String[] lines = line.split("\n");

for(String data:lines) {
if(data.trim().startsWith("\"movieNm\"")) {

System.out.println(data.trim());
}
}

System.out.println(line);     //json 데이터는 한줄로 만들어지기 때문에 그냥 한 줄만 읽어도 모든 데이터가 출력된다.

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("에러:"+e.getMessage());
}finally {
if(br !=null) try {br.close();}catch(IOException e) {};
}
}



}

 

결과 (제목만 출력되지 않아 해당 코드는 다시...)

 

 

 

 

JsonEx01.java  - json문자열을 배열로 변경하기
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonEx01 {

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

//json 문자열  =>  배열
String strJson ="[ 8, 9, 6, 2, 9 ]";

JSONParser parser = new JSONParser();

try {
JSONArray arr = (JSONArray)parser.parse(strJson);      //내부가 배열화 되어있으면 배열로 바꿔준다

System.out.println(arr);
System.out.println(arr.size());
System.out.println(arr.get(0));
System.out.println(arr.get(1));
System.out.println(arr.get(2));

//분석이 훨씬 편리하다
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}

결과

 

 

JSonEx02.java - json문자열을 객체로 변경하기
public class JsonEx02 {


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


//json 문자열 => 객체
String strJson ="{ \"data1\": \"value1\", \"data2\": \"value2\"}";



JSONParser parser = new JSONParser();

try {

JSONObject obj= (JSONObject)parser.parse(strJson);

System.out.println(obj);
System.out.print((String)obj.get("data1"));
System.out.print((String)obj.get("data2"));
//분석이 훨씬 편리하다
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}

결과

 

JsonEx03.java - json문자열을 객체로 변경하기 (2)
public class JsonEx03 {


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


//json 문자열 => 객체
String strJson ="[{ \"data1\": \"value1\", \"data2\": \"value2\"} , { \"data3\": \"value3\", \"data4\": \"value4\"}]";



JSONParser parser = new JSONParser();

try {

JSONArray arr = (JSONArray)parser.parse(strJson);


//System.out.println(arr);
//System.out.println(arr.size());
System.out.println(arr.get(0));
System.out.println(arr.get(1));



/*System.out.println(obj);
System.out.print((String)obj.get("data1"));
System.out.print((String)obj.get("data2"));*/
//분석이 훨씬 편리하다
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}

결과

 

 

JSonEx04.java  - json문자열을 객체로 변경하기 (3)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonEx04 {

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

//json 문자열  =>  객체


BufferedReader br=null;



try {
URL url = new URL(" http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchWeeklyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230916 ");
br=new BufferedReader(new InputStreamReader(url.openStream()));

String line = br.readLine();

JSONParser parser = new JSONParser();
JSONObject root =(JSONObject)parser.parse(line);

JSONObject boxOfficeResult =(JSONObject)root.get("boxOfficeResult");    //박스오피스 결과물 (객체)
//System.out.println(boxOfficeResult);


JSONArray weeklyBoxOfficeLists =(JSONArray)boxOfficeResult.get("weeklyBoxOfficeList");   // 주간 박스오피스 리스트 (배열)
//System.out.println(weeklyBoxOfficeLists.get(0));

JSONObject obj =(JSONObject)weeklyBoxOfficeLists.get(1);    
System.out.println((String)obj.get("movieNm"));      //객체 출력

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}

 

결과: 왜 data2가 먼저오고 data1이 오는 지 모르겠음


< 프로젝트 >

1. wireframe (완)

2. UML (완)

3. ERD (완)

=> 수정 진행하기

2. 코딩

3. 완료보고

 


해결1.구구단

해결2. 콤보박스 우편번호

해결3. 다이얼로그 우편번호

728x90
반응형

'Programming > JAVA' 카테고리의 다른 글

JVM과 JAVA 실행방식  (0) 2024.02.06
[JAVA] 데이터 출력 (xml, json)  (0) 2023.09.21
[JAVA]GUI(5) - Layout  (0) 2023.09.18
[JAVA] GUI(4)  (0) 2023.09.15
[JAVA] GUI(3)  (0) 2023.09.14