忍者ブログ

アンドロイドのあれこれ

AndroidからHTTP通信でGET、POST
まずはマニフェストにインターネット接続権限を追加します。
<!-- AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="alone.advent.android.app"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Light.NoTitleBar"
        >
(略)

※ここで注意
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-sdk android:minSdkVersion="4" />
ではなく、android.permission.INTERNETを追加するのはsdkバーションが書かれている
<uses-sdk android:minSdkVersion="4" /> の以下だよ!
    <uses-sdk android:minSdkVersion="4" />
    <uses-permission android:name="android.permission.INTERNET" />
permission追加しても通信できないよっていう人は確認してください。

- マルチスレッドでHTTP送信
public class MainActivity extends Activity {
    private static final String sURL = "http://www.sample.com";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //GETリクエストの場合
        //Thread myThread = new Thread(null, requestGetRunn, "RequestGetRunnable");
        //POSTリクエストの場合
        Thread myThread = new Thread(null, requestPostRunn, "RequestPostRunnable");
        myThread.start();
    }
    
    private Runnable requestPostRunn = new Runnable()
    {
        public void run(){
            String responseStr = "";
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(sURL);
            
            //Postパラメータを作る
            List<NameValuePair> params = new ArrayList<NameValuePair>(1);
            params.add(new BasicNameValuePair("param1", "value1"));
            params.add(new BasicNameValuePair("param2", "value2"));
            
            HttpResponse response = null;
            ByteArrayOutputStream outstream = null;
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
                response = client.execute(post);
                outstream = new ByteArrayOutputStream();
                response.getEntity().writeTo(outstream);
                if (response != null && 
                        response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    responseStr = outstream.toString();
                }
            } catch (Exception e) {
                Log.v("ERROR-LOG", e.getMessage());
            }

            //ハンドラーにメッセージ送信
            Message mess = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("RESULT",responseStr);
            mess.setData(bundle);
            requestHand.sendMessage(mess);
        }
    };
    
    private Runnable requestGetRunn = new Runnable()
    {
        public void run() {
            String responseStr = "";
            
            //Getのuriとクエリーのパラメータ作成
            Uri.Builder uriBuilder = new Uri.Builder();
            uriBuilder.scheme("http");
            uriBuilder.authority("sample.com");
            uriBuilder.path("/path");
            uriBuilder.appendQueryParameter("param1", "value1");
            uriBuilder.appendQueryParameter("param2", "value2");
            
            String uriStr = uriBuilder.toString();
            
            HttpUriRequest get = new HttpGet(uriStr);
            
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = null;
            ByteArrayOutputStream outstream = null;
            try {
                response = client.execute(get);
                outstream = new ByteArrayOutputStream();
                response.getEntity().writeTo(outstream);
                if (response != null && 
                        response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    responseStr = outstream.toString();
                }
            } catch (Exception e) {
                Log.v("ERROR-LOG", e.getMessage());
            }

            //ハンドラーにメッセージ送信
            Message mess = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("RESULT",responseStr);
            mess.setData(bundle);
            requestHand.sendMessage(mess);
        }
    };
    
    private Handler requestHand = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            String result = msg.getData().getString("RESULT");
            Log.v("TESTLOG", result);
        }
    };
}

COMMENT
NAME
TITLE
MAIL (非公開)
URL
EMOJI
Vodafone絵文字 i-mode絵文字 Ezweb絵文字
COMMENT
PASS (コメント編集に必須です)
SECRET
管理人のみ閲覧できます
 
PR
© Android Advent
powered by 忍者ツールズ / 忍者ブログ / [PR]