일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- pbkdf2-password
- rest-assured
- 다중 서버 명령
- OOP
- MEAN stack
- node
- multidex
- memory structure
- event-driven
- window
- MaridDB
- instance
- Linux
- react-native
- Mongo
- ssh key
- Git
- Setup
- PBKDF2
- Express
- Mongoose
- API테스트
- Modulization
- Android
- proguard
- centos
- 64k method
- elemMatch
- iIntelliJ
- Java
Archives
- Today
- Total
천줄코딩도 한 걸음부터
Android로 Node.js 서버에 GET, POST 요청하기 본문
Android MainActivity 부분
1. GET / 데이터 받기
public class MainActivity extends AppCompatActivity { private TextView tvData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvData = (TextView)findViewById(R.id.textView); Button btn = (Button)findViewById(R.id.httpTest); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new JSONTask().execute("http://192.168.25.16:3000/users"); } }); } public class JSONTask extends AsyncTask{ @Override protected String doInBackground(String... urls) { try { JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("user_id", "androidTest"); jsonObject.accumulate("name", "yun"); HttpURLConnection con = null; BufferedReader reader = null; try{ //URL url = new URL("http://192.168.25.16:3000/users"); URL url = new URL(urls[0]); con = (HttpURLConnection) url.openConnection(); con.connect(); InputStream stream = con.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line = ""; while((line = reader.readLine()) != null){ buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(con != null){ con.disconnect(); } try { if(reader != null){ reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); tvData.setText(result); } } } 2. POST / Body에 데이터 붙여 보내고 받기
public class MainActivity extends AppCompatActivity { private TextView tvData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvData = (TextView)findViewById(R.id.textView); Button btn = (Button)findViewById(R.id.httpTest); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new JSONTask().execute("http://192.168.25.16:3000/post"); } }); } public class JSONTask extends AsyncTask{ @Override protected String doInBackground(String... urls) { try { JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("user_id", "androidTest"); jsonObject.accumulate("name", "yun"); HttpURLConnection con = null; BufferedReader reader = null; try{ //URL url = new URL("http://192.168.25.16:3000/users"); URL url = new URL(urls[0]); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Cache-Control", "no-cache"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "text/html"); con.setDoOutput(true); con.setDoInput(true); con.connect(); OutputStream outStream = con.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream)); writer.write(jsonObject.toString()); writer.flush(); writer.close(); InputStream stream = con.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line = ""; while((line = reader.readLine()) != null){ buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(con != null){ con.disconnect(); } try { if(reader != null){ reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); tvData.setText(result); } } } Node.js 부분
1. app.js
const express = require('express'); const app = express(); let users = [ { id: 1, name: 'alice' }, { id: 2, name: 'bek' }, { id: 3, name: 'chris' } ] app.get('/users', (req, res) => { console.log('who get in here/users'); res.json(users) }); app.post('/post', (req, res) => { console.log('who get in here post /users'); var inputData; req.on('data', (data) => { inputData = JSON.parse(data); }); req.on('end', () => { console.log("user_id : "+inputData.user_id + " , name : "+inputData.name); }); res.write("OK!"); res.end(); }); app.listen(3000, () => { console.log('Example app listening on port 3000!'); });서버 통신을 구현하며 계속 FileNotFountException에러가 나서 하루동안 애를 먹었다.
스프링에서는 같은 url로 GET과 POST요청을 받아들였던 것 같은데 url 중복으로 생긴 문제였나보다.
url을 다르게 지정하니 문제가 해결되었다.
'Others' 카테고리의 다른 글
Java는 call-by-reference 방식을 지원하는가? (0) | 2017.06.16 |
---|---|
IntelliJ IDEA 국제학생증(ISIC)으로 무료 계정 등록하기 (0) | 2017.06.15 |
Android 64K 메서드제한 오류 해결 (0) | 2017.05.13 |
git 접근 권한 에러 - remote: HTTP Basic: Access denied (0) | 2017.04.27 |
텍스트 에디터 - Atom (0) | 2017.04.19 |