Kotlin(코틀린)/Code snippet
[코틀린(Kotlin)] http 통신 예제 파이어베이스(Firebase)
2022. 6. 1. 14:34반응형
참고하면 좋을 자료
- Firebase로 로그인 기능 구현
1. 먼저, http통신을 하기 전, Firebase에서 제공한 json을 셋팅해야한다.
파이어베이스 관련 Json
{
implementation platform('com.google.firebase:firebase-bom:30.0.1')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-firestore'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
2. 그리고 google-services.json을셋팅해줘야된다.
https://m.post.naver.com/viewer/postView.naver?volumeNo=33234123&memberNo=25379965
위의 블로그를 참고해서, google-services.json을 다운받고, 적절한 위치에 위치시키자.
(파이어베이스에서 직접 가져와야됨)
각자 파이어베이스에서 google-services.json을
소스코드
MainActivity.kt
package com.example.myapplication_kotlin2_https
import android.os.Build
import android.os.Bundle
import android.os.StrictMode
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.firestore.FirebaseFirestore
import com.example.myapplication_kotlin2_https.databinding.ActivityMainBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
var TAG = "OLIVER1004"
val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
val api = APIS.create();
lateinit var firestore:FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
firestore = FirebaseFirestore.getInstance()
val user = hashMapOf(
"first" to "Ada",
"last" to "Lovelace",
"born" to 1815
)
// 데이터 쓰기
firestore.collection("users")
.add(user)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding document", e)
}
// 데이터 읽기
firestore.collection("read_user")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents.", exception)
}
// 바인딩을 하기위해, 뷰와 해당 Activity를 바인딩 설정(set)한다.
setContentView(binding.root)
// 퍼미션 문제 떄문에, 아래를 적용.
if (Build.VERSION.SDK_INT > 9) {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
}
var factory:XmlPullParserFactory = XmlPullParserFactory.newInstance()
var parser:XmlPullParser = factory.newPullParser()
//GET 버튼 클릭 시, 수행하는 함수
binding.getbutton.setOnClickListener {
var str:String ?= null;
// API를 가져올 url 등록,
// 여기에 인증키(authKey)값, 반환타입, 시작페이지(startPage)
// 최대 표시될 내용물의 수(display) 등이 포함된다. (공식 API사이트에 명시되어잇음)
val url = URL(
"http://openapi.work.go.kr/opi/opi/opia/wantedApi.do?" +
"returnType=xml&startPage=1&display=10&callTp=L&" +
"authKey=WNL1POQRW61BKHAAN8XJJ2VR1HK"
)
// Debug로그에 출력
Log.d(TAG, "GET BUTTON onClick")
// url.openConnection 함수를 통해, 해당
with(url.openConnection() as HttpURLConnection) {
//with 키워드는, "url.openConnection()"의 멤버를
// 암묵적으로 사용하는 것을 의미한다.
// 즉 아래의 requestMethod는 url.openConnection().requestMethod와 같다.
// 요청타입은 GET
requestMethod = "GET" // optional default is GET
Log.d(TAG, "openConnection")
Log.d(TAG, "Sent 'GET' request to URL :")
// 응답 내용을 가져오기 위해, bufferedReader를 통해 가져온다.
inputStream.bufferedReader().use {
it.lines().forEach { line ->
Log.d(TAG, line)
// 화면 출력을 담당하는 str에
// 응답 결과물 line을 저장.
str = line
}
}
}
// 해당 내용을 'text'에 설정한다.
// 즉, 화면 앱에 표시가 된다.
binding.text.setText(str);
}
binding.postbutton.setOnClickListener {
binding.text.setText("clear");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication_kotlin2_https">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication_kotlin2_https"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/idedt"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="아이디 입력"
tools:layout_editor_absoluteY="55dp" />
<EditText
android:id="@+id/nickedt"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="닉네임입력"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.482"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="134dp" />
<EditText
android:id="@+id/pwdedt"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="패스워드입력"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.508"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="212dp" />
<Button
android:layout_gravity="center"
android:id="@+id/getbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="get요청"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="341dp" />
<Button
android:layout_gravity="center"
android:id="@+id/postbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="post요청"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="460dp" />
<TextView
android:layout_gravity="center"
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="초기값"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="611dp" />
</LinearLayout>
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.10'
}
}
plugins {
id 'com.android.application' version '7.1.3' apply false
id 'com.android.library' version '7.1.3' apply false
id 'org.jetbrains.kotlin.android' version '1.6.21' apply false
}
allprojects {
repositories {
// Check that you have the following line (if not, add it):
// google() // Google's Maven repository
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
app/build.gra
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdk 32
defaultConfig {
applicationId "com.example.myapplication_kotlin2_https"
minSdk 30
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = '11'
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.6.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation platform('com.google.firebase:firebase-bom:30.0.1')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-firestore'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
출력화면
logcat 화면
2022-06-01 14:36:51.219 26127-26127/com.example.myapplication_kotlin2_https D/OLIVER1004: OJrvVAT4KG5EJIRUNytO => {read_name="read_user"} 2022-06-01 14:37:01.345 26127-26127/com.example.myapplication_kotlin2_https D/OLIVER1004: DocumentSnapshot added with ID: gEZPCDwW3Is1Oz05Ry67 2022-06-01 14:37:04.861 26127-26127/com.example.myapplication_kotlin2_https D/OLIVER1004: GET BUTTON onClick 2022-06-01 14:37:04.863 26127-26127/com.example.myapplication_kotlin2_https D/OLIVER1004: openConnection 2022-06-01 14:37:04.863 26127-26127/com.example.myapplication_kotlin2_https D/OLIVER1004: Sent 'GET' request to URL : 2022-06-01 14:37:05.069 26127-26127/com.example.myapplication_kotlin2_https D/OLIVER1004: <?xml version="1.0" encoding="UTF-8"?><wantedRoot><total>89712</total><startPage>1</startPage><display>10</display><wanted><wantedAuthNo>K171222206010007</wantedAuthNo><company>글로벌특장</company><title>크레인수리 및 정비</title><salTpNm>월급</salTpNm><sal>250만원</sal><minSal>2500000</minSal><maxSal>0</maxSal><region>충북 충주시</region><holidayTpNm>주5일근무</holidayTpNm><minEdubg>학력무관</minEdubg><career>신입</career><regDt>22-06-01</regDt><closeDt>채용시까지 22-07-31</closeDt><infoSvc>VALIDATION</infoSvc><wantedInfoUrl>http://www.work.go.kr/empDetailRedirect.do?wantedAuthNo=K171222206010007</wantedInfoUrl><wantedMobileInfoUrl>https://m.work.go.kr/regionJobsWorknet/jobDetailView2.do?srchInfotypeNm=VALIDATION&srchWantedAuthNo=K171222206010007</wantedMobileInfoUrl><smodifyDtm>202206011430</smodifyDtm><zipCd>27443</zipCd><strtnmCd>431304514508</strtnmCd><basicAddr>충청북도 충주시 금가면 문산새터길 169</basicAddr><detailAddr>문산리</detailAddr><empTpCd>10</empTpCd><jobsCd>811301</jobsCd><prefCd></prefCd></wanted><wanted><wantedAuthNo>K172112206010007</wantedAuthNo><company>선진정공(주)</company><title>품질관리 공정검사원(현장직) 모집</title><salTpNm>시급</salTpNm><sal>9160원 ~ 10500원</sal><minSal>9160</minSal><maxSal>10500</maxSal><region>충남 당진시</region><holidayTpNm>주5일근무</holidayTpNm><minEdubg>학력무관</minEdubg><career>경력</career><regDt>22-06-01</regDt><closeDt>채용시까지 22-07-31</closeDt><infoSvc>VALIDATION</infoSvc><wantedInfoUrl>http://www.work.go.kr/empDetailRedirect.do?wantedAuthNo=K172112206010007</wantedInfoUrl><wantedMobileInfoUrl>https://m.work.go.kr/regionJobsWorknet/jobDetailView2.do?srchInfotypeNm=VALIDATION&srchWantedAuthNo=K172112206010007</wantedMobileInfoUrl><smodifyDtm>202206011429</smodifyDtm><zipCd>31743</zipCd><strtnmCd>442704595431</strtnmCd><basicAddr>충청남도 당진시 신평면 신평길 225-132</basicAddr><detailAddr>선진정공(주)</detailAddr><empTpCd>10</empTpCd><jobsCd>158500</jobsCd><prefCd></prefCd></wanted><wanted><wantedAuthNo>K172112206010006</wantedAuthNo><company>선진정공(주)</company><title>굴삭기 품질 관리 및 정비원 정규직 모집 (현장직...</title><salTpNm>연봉</salTpNm><sal>3000만원 ~ 3700만원</sal><minSal>30000000</minSal><maxSal>37000000</maxSal><region>충남 당진시</region><holidayTpNm>주5일근무</holidayTpNm><minEdubg>학력무관</minEdubg><career>관계없음</career><regDt>22-06-01</regDt><closeDt>채용시까지 22-07-31</closeDt><infoSvc>VALIDATION</infoSvc><wantedInfoUrl>http://www.work.go.kr/empDetailRedirect.do?wantedAuthNo=K172112206010006</wantedInfoUrl><wantedMobileInfoUrl>https://m.work.go.kr/regionJobsWorknet/jobDetailView2.do?srchInfotypeNm=VALIDATION&srchWantedAuthNo=K172112206010006</wantedMobileInfoUrl><smodifyDtm>202206011425</smodifyDtm><zipCd>31743</zipCd><strtnmCd>442704595431</strtnmCd><basicAddr>충청남도 당진시 신평면 신평길 225-132</basicAddr><detailAddr>선진정공(주)</detailAddr><empTpCd>10</empTpCd><jobsCd>811600</jobsCd><prefCd></prefCd></wanted><wanted><wantedAuthNo>K172112206010005</wantedAuthNo><company>(주)알테크노메탈</company><title>[영업팀] 정규직 사원 모집</title><salTpNm>연봉</salTpNm><sal>3000만원</sal><minSal>30000000</minSal><maxSal>0</maxSal><region>충남 당진시</region><holidayTpNm>주5일근무</holidayTpNm><minEdubg>학력무관</minEdubg><career>관계없음</career><regDt>22-06-01</regDt><closeDt>22-06-19</closeDt><infoSvc>VALIDATION</infoSvc><wantedInfoUrl>http://www.work.go.kr/empDetailRedirect.do?wantedAuthNo=K172112206010005</wantedInfoUrl><wantedMobileInfoUrl>https://m.work.go.kr/regionJobsWorknet/jobDetailView2.do?srchInfotypeNm=VALIDATION&srchWantedAuthNo=K172112206010005</wantedMobileInfoUrl><smodifyDtm>202206011413</smodifyDtm><zipCd>31721</zipCd><strtnmCd>442704595279</strtnmCd><basicAddr>충청남도 당진시 송악읍 부곡공단4길 28-304</basicAddr><detailAddr>(주 |
반응형
'Kotlin(코틀린) > Code snippet' 카테고리의 다른 글
[코틀린(Kotlin)] suspend함수 예제 콜백함수 예제, thread (0) | 2022.09.13 |
---|---|
[Compose] 컴포즈 예제모음 (Main) (0) | 2022.05.30 |