티스토리 뷰

2018/10/09 - [프로그래밍/안드로이드] - [안드로이드] Url에 요청해서 Json 받아오기 (Get)

에서도 다루었지만 이번엔 여러가지 JSON요청방식, 그리고 class를 따로 분리하는 방법을 쓴다.

(XML은 안바뀌었다)


 - 메인 엑티비티

package com.example.acid.jsonpost;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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);
}

public class threadforce extends Thread{
@Override
public void run() {
super.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);
}
}

@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();
//JSON 형태로 보내기
Thread threadPost = new Thread(this);
threadPost.start();

break;

case R.id.button2: // Get 방식 Json 가져오기 (Thread를 클래스 생성한 방식) httpCon.connect();으로 연결하는 방식
Toast.makeText(getApplicationContext(), "button2을 눌렀습니다.", Toast.LENGTH_LONG).show();
getEditText = editTextGet.getText().toString();
try {
threadforce thread =
new threadforce();
thread.start();

} catch (Exception e) {
e.printStackTrace()
;
}

break;

case R.id.button3: // 연결 Class 분리 한 방식 => Class는 Thread가 아니다.
Toast.makeText(getApplicationContext(), "테스트버튼.", Toast.LENGTH_LONG).show();
getEditText = editTextGet.getText().toString();
try {
Thread thread =
new Thread(new Runnable() {

@Override
public void run() {
//생성할때 param값 넣어줌
getHttpConnection getConnectionData = new getHttpConnection(getEditText);
String threadResult = getConnectionData.httpconnect();
//Handler는 Thread안에서 돌아야 한다.
Message message = mHandler.obtainMessage(102, threadResult);
mHandler.sendMessage(message);

}
})
;
thread.start();

} catch (Exception e) {
e.printStackTrace()
;
}
break;
} //Switch
}


@Override
public void run() {
String address =
"http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=";
URL url = null;
try {
url =
new URL(address);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Cache-Control", "no-cache");
httpCon.setRequestProperty("Content-Type", "application/json");
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setDoOutput(true); //outputstream으로 받겠다
httpCon.setDoInput(true); //InputStream으로 받겠다

//JSON으로 만듬
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "paul rudd");
JSONArray jsonArray = new JSONArray();
jsonArray.put("I Love You Man");
jsonArray.put("Role Models");
jsonObject.put("movies", jsonArray );
String param = jsonObject.toString();

//방식1
// OutputStreamWriter osw = new OutputStreamWriter(httpCon.getOutputStream());
// osw.write(param);
// osw.flush();
// osw.close();

OutputStream os = httpCon.getOutputStream();
os.write(param.getBytes("UTF-8"));
os.flush();
os.close();

int resultCode = httpCon.getResponseCode();
if (resultCode != 200) {

}
else {
InputStreamReader isr =
new InputStreamReader(httpCon.getInputStream(), "UTF-8");
BufferedReader bf = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = bf.readLine()) != null) {
sb.append(line)
;
}

httpCon.disconnect()
;
Message msg = mHandler.obtainMessage(102, sb.toString());
mHandler.handleMessage(msg);


}
}
catch (Exception e) {
e.printStackTrace()
;
}
}

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;

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

break;
}
}
}
}
}

getConnectionData.class

package com.example.acid.jsonpost;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class getHttpConnection {

private String getEditText;
private String resultData;

public getHttpConnection(String getEditText) {
this.getEditText = getEditText;

}

public String httpconnect(){
//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();
}
return resultData;
}


}

이전과 달리 클래스를 분리한 것도 있고, outputstream으로 실행하는 방법

그리고 Thread를 새로 생성해서 돌리는 방법등 여러가지를 시도해 본 코드이다. 

최종적으로는 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
글 보관함