facebook twitter hatena line email

Android/HttpRequest通信/DefaultHttpClient/サンプル

提供: 初心者エンジニアの簡易メモ
2018年8月6日 (月) 11:29時点におけるAdmin (トーク | 投稿記録)による版 (Admin がページ「Android/HttpRequest通信/DefaultHttpClient」を「Android/HttpRequest通信/DefaultHttpClient/サンプル」に、リダイレクトを残さずに移動しました)

移動: 案内検索

HTTP通信サンプル

httpsも可能なように作成

  • AndroidManifest.xml

以下追加

<uses-permission android:name="android.permission.INTERNET" />
  • SpHttpRequest.java
package info.nonip.android.entity;
import android.os.Build;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
 * スマホHttpRequest通信クラス
 *
 * @ex
 *     SpHttpRequest http = new SpHttpRequest("http://www.google.com/");
 *     http.setMethod(SpHttpRequest.METHOD_POST);
 *     http.addParam("hoge", "piyo");
 *     String response = http.exec();
 * 必須:<uses-permission android:name="android.permission.INTERNET" />
 */
public class SpHttpRequest {
    public static int METHOD_GET = 0;
    public static int METHOD_POST = 1;
    // URL
    private String mUrl = "http://example.com/";
    // メソッド
    private int mMethod = METHOD_GET;
    // パラメータを生成
    private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
    // 文字コード
    private String mCharset = "UTF-8";
    // ua
    private String mUserAgent = "Mozilla/5.0 (Linux; U; Android 2.3.3; ja-jp";
    // ステータスコード
    private int mStatusCode;
    // construct
    public SpHttpRequest(String url) {
        mUrl = url;
        mUserAgent = "Mozilla/5.0 (Linux; U; Android " + Build.VERSION.RELEASE + "; ja-jp; " + Build.MODEL + " Build/A30";
    }
    // メソッド設定
    public void setMethod(int method) {
        mMethod = method;
    }
    // 文字コード設定
    public void setCharset(String charset) {
        mCharset = charset;
    }
    // UserAgent設定
    public void setUserAgent(String ua) {
        mUserAgent = ua;
    }
    // パラメータ追加
    public void addParam(String key, String value) {
Log.d("SpHttpRequest", "addParam " + key + "=" + value);
        mParams.add(new BasicNameValuePair(key, value));
    }
    // リクエスト処理実行
    public String exec() {
        if (mMethod == METHOD_POST) {
            return execPost();
        } else {
            return execGet();
        }
    }
    // リクエストGET
    private String execGet() {
Log.d("SpHttpRequest", "methode=get");
        String queries = URLEncodedUtils.format(mParams, mCharset);
        String url = mUrl;
        if (queries != "") {
            url += "?" + queries;
        }
Log.d("SpHttpRequest", "url=" + url);
        HttpGet httpGet = new HttpGet(url);
        return execRequest(httpGet);
    }
    // リクエストPOST
    private String execPost() {
Log.d("SpHttpRequest", "methode=post");
Log.d("SpHttpRequest", "url=" + mUrl);
        try {
            HttpPost httpPost = new HttpPost(mUrl);
            // パラメータを設定
            httpPost.setEntity(new UrlEncodedFormEntity(mParams, mCharset));
            return execRequest(httpPost);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
    // HttpsClientインスタンス取得
    private DefaultHttpClient getHttpsClient() {
        // http登録
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // https登録
        SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
        // httpパラメータ登録
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, mCharset);
        // Clientロード
        DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
        return httpClient;
    }
    // リクエストコア処理
    private String execRequest(HttpRequestBase http) {
        try {
            // HttpClientロード
            DefaultHttpClient httpClient = new DefaultHttpClient();
            // httpsの時
            if (mUrl.matches("https")) {
Log.d("SpHttpRequest", "https");
                // HttpsClientインスタンス取得
                httpClient = getHttpsClient();
            }
            // UserAgent設定
            httpClient.getParams().setParameter("http.useragent", mUserAgent);
Log.d("SpHttpRequest", "useragent=" + mUserAgent);
            // リクエスト実行
            HttpResponse httpResponse = httpClient.execute(http);
            // ステータスコードを取得
            mStatusCode = httpResponse.getStatusLine().getStatusCode();
Log.d("SpHttpRequest", "statusCode=" + mStatusCode);
            // レスポンスを取得
            HttpEntity entity = httpResponse.getEntity();
            String response = EntityUtils.toString(entity);
            // リソースを解放
            entity.consumeContent();
            // クライアントを終了させる
            httpClient.getConnectionManager().shutdown();
Log.d("SpHttpRequest", "response=" + response);
            return response;
        } catch (ClientProtocolException e) {
Log.e("SpHttpRequest", "ClientProtocolException=" + e.getMessage());
            throw new RuntimeException(e);
        // HOST不明エラー,AndroidManifestにInternetを追加しているか確認
        } catch (UnknownHostException e) {
Log.e("SpHttpRequest", "UnknownHostException=" + e.getMessage());
            throw new RuntimeException(e);
        } catch (IOException e) {
Log.e("SpHttpRequest", "IOException=" + e.getMessage());
            throw new RuntimeException(e);
        } catch (Exception e) {
Log.e("SpHttpRequest", "Exception=" + e.getMessage());
            return null;
        }
    }
    // ステータスコード取得
    public int getStatusCode() {
        return mStatusCode;
    }
}

import org.apache.httpがインポートできないとき

以下のjarをプロジェクトのlibsへ追加する

Android/Sdk/platforms/android-23/optional/org.apache.http.legacy.jar

gradleだと

dependencies {
   implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.1'
}