ArkTS 네트워크 프로그래밍과 Git 활용 방법

Git 기본 명령어

주요 참고 자료

  • Gitee 코드 업로드 상세 가이드
  • GitBash 사용법 완벽 가이드
  • Gitee 팀 프로젝트 협업 개발 절차 예시
  • Git 기본 명령어 사용법

자주 사용하는 작업

원격 저장소 복제

git clone https://gitee.com/username/repository.git

브랜치 매핑 관계 확인

git branch -a

develop 브랜치로 전환

원격 저장소 추가 및 이름 지정

git remote add origin https://gitee.com/username/repository.git

develop 브랜치에 코드 푸시

  1. 변경사항 스테이징 및 커밋
  2. git add .
    git commit -m '기능 구현 완료'
  3. 원격 저장소로 푸시
  4. git push -u origin develop

ArkTS HTTP 네트워킹

HTTP 요청 전송

GET 요청

import http from '@ohos.net.http';

const httpClient = http.createHttp();

httpClient.request({
    method: 'GET',
    url: 'https://api.example.com/data',
    header: {
        'Content-Type': 'application/json'
    }
}, (error, response) => {
    if (!error) {
        console.log('응답 데이터: ' + response.result);
    } else {
        console.error('요청 실패: ' + error.message);
    }
});

POST 요청

import http from '@ohos.net.http';

const httpClient = http.createHttp();

httpClient.request({
    method: 'POST',
    url: 'https://api.example.com/submit',
    header: {
        'Content-Type': 'application/json'
    },
    data: JSON.stringify({
        name: 'test',
        value: 123
    })
}, (error, response) => {
    if (!error) {
        console.log('응답: ' + response.result);
    } else {
        console.error('요청 실패: ' + error.message);
    }
});

응답 처리

JSON 데이터 파싱

httpClient.request({
    method: 'GET',
    url: 'https://api.example.com/json-data',
    header: {
        'Content-Type': 'application/json'
    }
}, (error, response) => {
    if (!error) {
        try {
            const jsonData = JSON.parse(response.result);
            console.log('파싱된 데이터: ' + jsonData.value);
        } catch (parseError) {
            console.error('JSON 파싱 실패: ' + parseError.message);
        }
    } else {
        console.error('요청 실패: ' + error.message);
    }
});

응답 헤더 처리

httpClient.request({
    method: 'GET',
    url: 'https://api.example.com/info',
    header: {
        'Accept': 'application/json'
    }
}, (error, response) => {
    if (!error) {
        console.log('Content-Type: ' + response.header['Content-Type']);
        const jsonData = JSON.parse(response.result);
        console.log('데이터: ', jsonData);
    } else {
        console.error('요청 실패: ' + error.message);
    }
});

에러 처리

기본 에러 처리

httpClient.request({
    method: 'GET',
    url: 'https://api.example.com/invalid',
    header: {
        'Content-Type': 'application/json'
    }
}, (error, response) => {
    if (!error) {
        console.log('응답: ' + response.result);
    } else {
        console.error('요청 실패: ' + error.message);
    }
});

HTTP 상태 코드별 처리

httpClient.request({
    method: 'GET',
    url: 'https://api.example.com/data',
    header: {
        'Content-Type': 'application/json'
    }
}, (error, response) => {
    if (!error) {
        console.log('응답: ' + response.result);
    } else {
        switch (error.status) {
            case 404:
                console.error('404 에러: 리소스를 찾을 수 없음');
                break;
            case 500:
                console.error('500 에러: 서버 내부 오류');
                break;
            default:
                console.error('요청 실패 - 상태 코드: ' + error.status);
        }
    }
});

로그인 상태 검증 컴포넌트

구현 접근법

  1. 컴포넌트 초기화 시 사용자 인증 상태 확인
  2. 인증 상태에 따라 UI 분기 처리
  3. 컴포넌트 종료 시 리소스 정리

코드 구현

@Entry
@Component
struct AuthComponent {
  @State authenticated: boolean = false;

  onInit() {
    this.verifyAuthStatus();
  }

  onDestroy() {
    this.releaseResources();
  }

  verifyAuthStatus() {
    this.authenticated = checkUserAuthentication();
    
    if (!this.authenticated) {
      this.navigateToAuth();
    }
  }

  navigateToAuth() {
    router.push({
      url: 'pages/AuthenticationPage'
    });
  }

  releaseResources() {
    console.log('리소스 해제 중...');
  }

  build() {
    if (this.authenticated) {
      return this.renderMainInterface();
    } else {
      return this.renderAuthInterface();
    }
  }

  renderMainInterface() {
    return Column() {
      Text("환영합니다!").fontSize(30)
      Button("로그아웃").onClick(() => {
        this.performLogout();
      })
    }
  }

  renderAuthInterface() {
    return Column() {
      Text("로그인이 필요합니다.").fontSize(30)
      Button("로그인").onClick(() => {
        this.performLogin();
      })
    }
  }

  performLogin() {
    this.authenticated = true;
    this.verifyAuthStatus();
  }

  performLogout() {
    this.authenticated = false;
    this.verifyAuthStatus();
  }
}

function checkUserAuthentication(): boolean {
  return false;
}

동작 설명

  • onInit: 컴포넌트 초기화 시 인증 상태 확인
  • verifyAuthStatus: 사용자 인증 상태 검증 및 분기 처리
  • navigateToAuth: 인증 페이지로 네비게이션
  • build: 인증 상태에 따른 UI 렌더링
  • performLogin/performeLogout: 로그인/로그아웃 동작 처리

태그: ArkTS HTTP Git HarmonyOS 네트워크프로그래밍

9월 21일 15:31에 게시됨