티스토리 뷰

1. 메니페스트에 인터넷 권한 


<uses-permission android:name="android.permission.INTERNET"/>


2. xml 만들기

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="데이터 가져오기"
android:textAlignment="center" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="JSON" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="테스트" />

</LinearLayout>

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="값을 넣으세요." />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Get방식 api 가져오기" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Get Json" />
</LinearLayout>

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="800" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="* 결과창"
android:textSize="18sp"
android:textStyle="bold" />

<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView" />
</LinearLayout>
</LinearLayout>



3. 코드쓰기


package com.example.acid.jsonpost;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutput;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Runnable {

Button button;
TextView textView;
EditText editText;

Button buttonGet;
EditText editTextGet;

TextView textViewSet;

Button buttonTest;

String getEditText = "";
String resultData ="";



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Result TextView
textView = findViewById(R.id.textView3);

//Post Json 요청
button = findViewById(R.id.button);
editText = findViewById(R.id.editText);

//Get Json 요청
buttonGet = findViewById(R.id.button2);
editTextGet = findViewById(R.id.editText2);

textViewSet = findViewById(R.id.textView);

buttonTest = findViewById(R.id.button3);

//setOnClick connect
button.setOnClickListener(this);
buttonTest.setOnClickListener(this);
buttonGet.setOnClickListener(this);
}

@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.button: // Json 보내기
Toast.makeText(getApplicationContext(), "button1을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editText.getText().toString();
resultData = JsonPost(getEditText);

textView.setText(resultData);
break;

case R.id.button2: // Get방식 Json 가져오기
Toast.makeText(getApplicationContext(), "button2을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editTextGet.getText().toString();
try {
Thread thread = new Thread(this);
thread.start();
} catch (Exception e) {
e.printStackTrace();
}


break;

case R.id.button3: //
Toast.makeText(getApplicationContext(), "테스트버튼.", Toast.LENGTH_LONG).show();

break;
} //Switch
}


public String JsonPost(String getEditText) {
return "";
}

@Override
public void run() {
//http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=805
String address = "http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=" + getEditText;
String resultData = "";

try {
URL url = new URL(address);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//GET or Post 설정
httpCon.setRequestMethod("GET");
//커넥션 타임아웃 설정 (서버 접속시 연결시간)
httpCon.setConnectTimeout(10 * 1000);
//Read시 타임아웃 설정
httpCon.setReadTimeout(10 * 1000);
// User-Agent 설정
httpCon.setRequestProperty("User-Agent", "Mozilla/9.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");

/* // Request Header값 셋팅 setRequestProperty(String key, String value)
httpCon.setRequestProperty("NAME", "name");
httpCon.setRequestProperty("MDN", "mdn");
httpCon.setRequestProperty("APPID", "appid");
// 서버 Response Data를 xml 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/xml");
// 서버 Response Data를 JSON 형식의 타입으로 요청.
httpCon.setRequestProperty("Accept", "application/json");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 text/html로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "text/html");
// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/xml");
// 타입설정(application/json) 형식으로 전송 (Request Body 전달시 application/json로 서버에 전달.)
httpCon.setRequestProperty("Content-Type", "application/json");
// 컨트롤 캐쉬 설정
httpCon.setRequestProperty("Cache-Control", "no-cache");
// 타입길이 설정(Request Body 전달시 Data Type의 길이를 정함.)
httpCon.setRequestProperty("Content-Length", "length")*/

//여기서 연결한다
httpCon.connect();

//Response code 불러오기
int code = httpCon.getResponseCode();
Log.d("Response Code", code + "");

if (code == 200) { //정상처리 200

//InputStream으로 읽어들인다.
InputStream response = httpCon.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(response, "UTF-8");
//버퍼 리더로 변환
BufferedReader bf = new BufferedReader(inputStreamReader);

StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
resultData = sb.toString();

Log.d("Json", resultData);

response.close();
bf.close();


} else { // 에러
resultData = "None";
}

httpCon.disconnect();




} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message message = mHandler.obtainMessage(101, resultData);
mHandler.sendMessage(message);
}

private final MyHandler mHandler = new MyHandler(this);
public static class MyHandler extends Handler{
private final WeakReference<MainActivity> weakReference;

public MyHandler(MainActivity mainActivity) {
weakReference = new WeakReference<MainActivity>(mainActivity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

MainActivity mainactivity = weakReference.get();

if (mainactivity != null) {
switch (msg.what) {

case 101:
String jsonString = (String)msg.obj;
String result = "";
try {
//String to Json
JSONObject jsonObj = new JSONObject(jsonString);
result = jsonObj.getString("firstAccumamnt");
} catch (JSONException e) {
e.printStackTrace();
}
mainactivity.textView.setText(result);

break;
}
}
}
}
}


주의점

Thread로 구현을 해야 한다. Task하고 Thread가 있는데 Thread가 범용성이 있는거 같아서 그쪽 코드를 참조했다.

작업을 완료하면 Handler로 보내서 Handler에서 구분된 코드로 작업을 실행한다.





공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함