AndroidでHTTPリクエストを送信する 質問する

AndroidでHTTPリクエストを送信する 質問する

あらゆる場所を検索しましたが、答えが見つかりませんでした。簡単な HTTP リクエストを行う方法はありますか? 自分の Web サイトの 1 つで PHP ページ/スクリプトをリクエストしたいのですが、Web ページを表示したくありません。

可能であれば、バックグラウンド(BroadcastReceiver)で実行したい

ベストアンサー1

アップデート

これは非常に古い回答です。私はもう Apache のクライアントを絶対に推奨しません。代わりに次のいずれかを使用してください。

元の回答

まず、ネットワークへのアクセス許可を要求し、マニフェストに次の内容を追加します。

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

最も簡単な方法は、Android にバンドルされている Apache http クライアントを使用することです。

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

別のスレッドで実行したい場合は、AsyncTask を拡張することをお勧めします。

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

次の方法でリクエストを行うことができます。

   new RequestTask().execute("http://stackoverflow.com");

おすすめ記事