package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
requestGeocode();
}
}).start();
}
});
}
public void requestGeocode() {
try {
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
String coord = "127.1234308,37.3850143";
String query = "https://naveropenapi.apigw.ntruss.com/map-reversegeocode/v2/gc?request=coordsToaddr&coords="
+ coord + "&sourcecrs=epsg:4326&output=json&orders=roadaddr&output=xml";
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn != null) {
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("X-NCP-APIGW-API-KEY-ID", "Client ID");
conn.setRequestProperty("X-NCP-APIGW-API-KEY", "Client Secret");
conn.setDoInput(true);
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
//textView.setText(stringBuilder);
Gson gson = new Gson();
Address address = gson.fromJson(String.valueOf(stringBuilder), Address.class);
String finalAddress = null;
finalAddress = address.results[0].region.area1.name;
finalAddress += address.results[0].region.area2.name;
finalAddress += address.results[0].region.area3.name;
finalAddress += address.results[0].region.area4.name;
finalAddress += address.results[0].land.addition0.value;
textView.setText(finalAddress);
bufferedReader.close();
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}