Wednesday, September 28, 2011

Android URLConnection POST Example

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
<?xml version="1.0" encoding="utf-8"?>
<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
<%@ page language="java" contentType="text/xml; charset=UTF-8"
    pageEncoding="EUC-KR"%>
<?xml version="1.0" encoding="utf-8" ?>
<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();
 }

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.