Android URLConnection POST Example
안드로이드에서 URLConnection을 이용하여 POST요청을 웹서버에 전달하는 예
안드로이드에서는 2가지 방식의 네트워크 연결방식을 제공한다.
1. 기존 자바에 포함되어 있는 자바 전통적인 방식 (Socket, URLConnection 등)
2. 기존 자바에는 없고 안드로이드에는 포함된 Apache 라이브러리(HttpClient)를 사용하는 방식
다음은 자바 전통적인 방식 중에서 URLConnection 을 이용한 방식으로 웹서버에 요청(POST방식)할 때 파라미터를 전달하는 안드로이드 프로그램의 예이다. Socket을 이용하여 네트워크에 접속하는 예는 여기를 참조하세요
AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.web.test"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidWeb"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
AndroidWeb.java(Activity class)
package android.web.test;
import java.net.*;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidWeb extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textview = (TextView) this.findViewById(R.id.textview);
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("홍길동", "UTF-8");
// Send data
URL url = new URL("http://192.168.123.100:80/HelloWeb/androidPost.jsp");
URLConnection conn = url.openConnection();
// If you invoke the method setDoOutput(true) on the URLConnection, it will always use the POST method.
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line = null;
String response = "";
while ((line = rd.readLine()) != null) {
response += line;
}
textview.setText(response);
wr.close();
rd.close();
}
catch (Exception e) {
}
}
}
androidPost.jsp
pageEncoding="EUC-KR"%>
<params>
<%
request.setCharacterEncoding("UTF-8");
String value1 = request.getParameter("key1");
String value2 = request.getParameter("key2");
System.out.println("key1="+value1);
System.out.println("key2="+value2);
%>
<param1><%=value1%></param1>
<param2><%=value2%></param2>
</params>
Android에서 JSON 문자열로 응답을 받아서 JSONArray, JSONObject를 사용하여 데이터를 다루는 예
package test.hello;
import java.io.*;
import java.net.*;
import java.net.*;
import org.json.*;
import android.app.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
public class HttpRequestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.network01);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String jsonStr = null;
TextView tv = (TextView)findViewById(R.id.textView1);
jsonStr = downloadHtml("http://192.168.10.112:8888/SampleWeb/mobile/mservice.jsp");
jsonStr = jsonStr.trim();
try{
JSONArray ja = new JSONArray(jsonStr);
for(int i=0;i<ja.length();i++){
JSONObject jobj = ja.getJSONObject(i);
int empno = jobj.getInt("empno");
String ename = jobj.getString("ename");
int deptno = jobj.getInt("deptno");
tv.append(empno+":"+ename+":"+deptno+"\n");
}
}catch(Exception ex){}
}
});
}
String downloadHtml(String addr){
StringBuilder html = new StringBuilder();
try{
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if(conn!=null){
conn.setConnectTimeout(10000);
conn.setUseCaches(false);
if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
while(true){
String line = br.readLine();
Log.i("httptest",line);
if(line==null) break;
html.append(line+"\n");
}
br.close();
}
conn.disconnect();
}
}catch(Exception ex){}
return html.toString();
}
}