liguofeng29’s blog

個人勉強用ブログだっす。

Androidのweb開発 - URLConnectionでリクエストを投げる

URLでリクエストを投げ、データを取得できる。

手順

  1. URLオブジェクトのopenConnectionメソッドでURLConnectionオブジェクトを取得する
  2. URLConnectionのパラメータと属性?を設置得する
  3. リクエスト

    • GET : connectメソッドで送信する
    • POST:URLConnectionオブジェクトのoutputストリームでリクエストパラメータを送信する
  4. webリソースを読み取る(ヘッダ部、データ部)

リクエストのヘッダ部設定

  • setAllowUserInteraction()
  • setDoInput
  • setDoOutput
  • setIfModifiedSince
  • setUseCaches
  • setRequestProperty(String key, String value) など

データ取得

  • Object getContent()
  • String hetHeaderField(String name)
  • getOutputStream()
  • getContentEncoding
  • getContentLength()
  • getContentType()
  • getDate()
  • getExpiration()
  • getLastmodified() など

GET,POSTリクエストサンプル

① AndroidManifest.xml(権限)

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

② activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/get"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GET" />
    <Button
        android:id="@+id/post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POST" />
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

③ RequestUtil.java

package com.example.liguofeng.urlconnectionsample;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * Created by liguofeng on 2016/01/11.
 */
public class RequestUtil {
    /**
     * getリクエストを送信する
     * @param url
     * @param params
     * @return
     */
    public static String sendGet(String url, String params) {
        String result = "";
        BufferedReader in = null;

        try{
            // URLオブジェクト生成
            URL realUrl = new URL(url + "?" + params);
            URLConnection conn = realUrl.openConnection();

            // ヘッダー
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 6.0; WIndows NT 5.1; SV1)");

            // 接続
            conn.connect();

            Map<String, List<String>> map = conn.getHeaderFields();

            for (String key : map.keySet()) {
                System.out.println(key + " : " + map.get(key));
            }

            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * postリクエストを送信する
     * @param url
     * @param params
     * @return
     */
    public static String sendPost(String url, String params) {
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;

        try{
            // URLオブジェクト生成
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // ヘッダー
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 6.0; WIndows NT 5.1; SV1)");
            // postの場合必要
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // 出力ストリーム
            out = new PrintWriter(conn.getOutputStream());
            // リクエストパラメータ
            out.print(params);
            out.flush();

            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}

④ MainActivity.java

package com.example.liguofeng.urlconnectionsample;

import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView text;
    Button get, post;
    String response;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                // Text表示
                text.setText(response);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);
        text = (TextView) findViewById(R.id.text);

        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        response = RequestUtil.sendGet("https://users.miraclelinux.com/technet/document/linux/tomcat/jsptest.jsp", "");
                        handler.sendEmptyMessage(0x123);
                    }
                }.start();

            }
        });

        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        response = RequestUtil.sendPost("https://users.miraclelinux.com/technet/document/linux/tomcat/jsptest.jsp", "name=1&name=2");
                        handler.sendEmptyMessage(0x123);
                    }
                }.start();
            }
        });
    }
}

f:id:liguofeng29:20160111220127g:plain