回答:
これは非常に古い答えです。もう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");Apache HttpClientを選択する明確な理由がない限り、java.net.URLConnectionを優先する必要があります。あなたはそれをウェブ上で使う方法の多くの例を見つけることができます。
元の投稿以降、Androidのドキュメントも改善しました:http : //developer.android.com/reference/java/net/HttpURLConnection.html
公式ブログでトレードオフについて話し合いました:http : //android-developers.blogspot.com/2011/09/androids-http-clients.html
注:AndroidにバンドルされているApache HTTPクライアントは、HttpURLConnectionに代わり廃止されました。詳しくは、Androidデベロッパーブログをご覧ください。
<uses-permission android:name="android.permission.INTERNET" />マニフェストに追加します。
次に、次のようにWebページを取得します。
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
}
finally {
     urlConnection.disconnect();
}別のスレッドで実行することもお勧めします。
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
    String responseString = null;
    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
            // Do normal input or output stream reading
        }
        else {
            response = "FAILED"; // See documentation for more info on response handling
        }
    } 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..
}
}応答処理とPOST要求の詳細については、ドキュメントを参照してください。
readStreamさえ定義されていません。
                    最も簡単な方法は、VolleyというAndroid libを使用することです
Volleyには次の利点があります。
ネットワーク要求の自動スケジューリング。複数の同時ネットワーク接続。標準のHTTPキャッシュコヒーレンスを備えた透過的なディスクおよびメモリレスポンスキャッシング。リクエストの優先順位付けのサポート。キャンセルリクエストAPI。単一のリクエストをキャンセルするか、キャンセルするリクエストのブロックまたはスコープを設定できます。再試行やバックオフなどのカスタマイズが容易。ネットワークから非同期的にフェッチされたデータをUIに正しく入力することを容易にする強力な順序付け。デバッグおよびトレースツール。
次のように簡単にhttp / httpsリクエストを送信できます。
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="http://www.yourapi.com";
        JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (null != response) {
                         try {
                             //handle your response
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                    }
                }
            }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        queue.add(request);この場合、「バックグラウンドでの実行」または「キャッシュの使用」を自分で検討する必要はありません。これらはすべてVolleyによってすでに行われているためです。
スレッド付き:
private class LoadingThread extends Thread {
    Handler handler;
    LoadingThread(Handler h) {
        handler = h;
    }
    @Override
    public void run() {
        Message m = handler.obtainMessage();
        try {
            BufferedReader in = 
                new BufferedReader(new InputStreamReader(url.openStream()));
            String page = "";
            String inLine;
            while ((inLine = in.readLine()) != null) {
                page += inLine;
            }
            in.close();
            Bundle b = new Bundle();
            b.putString("result", page);
            m.setData(b);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        handler.sendMessage(m);
    }
}Gson libを使用して、WebサービスがURLを要求するようにこれを作成しました。
クライアント:
public EstabelecimentoList getListaEstabelecimentoPorPromocao(){
        EstabelecimentoList estabelecimentoList  = new EstabelecimentoList();
        try{
            URL url = new URL("http://" +  Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            if (con.getResponseCode() != 200) {
                    throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
            estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
            con.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return estabelecimentoList;
}Gradle経由で利用できるこの素晴らしい新しいライブラリを見てください:)
build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
使用法:
new HttpRequestTask(
    new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
    new HttpRequest.Handler() {
      @Override
      public void response(HttpResponse response) {
        if (response.code == 200) {
          Log.d(this.getClass().toString(), "Request successful!");
        } else {
          Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
        }
      }
    }).execute();上記で提案されているようにVolleyを使用します。build.gradle(モジュール:app)に以下を追加します
implementation 'com.android.volley:volley:1.1.1'以下をAndroidManifest.xmlに追加します。
<uses-permission android:name="android.permission.INTERNET" />そしてあなたにアクティビティコードに以下を追加してください:
public void httpCall(String url) {
    RequestQueue queue = Volley.newRequestQueue(this);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // enjoy your response
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // enjoy your error status
                }
    });
    queue.add(stringRequest);
}それはhttpクライアントを置き換え、それは非常に簡単です。
これは、AndroidのHTTP Get / POSTリクエストの新しいコードです。HTTPClient私の場合のように、価格は安く、利用できない場合があります。
まず、build.gradleに2つの依存関係を追加します。
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'次に、このコードASyncTaskをdoBackgroundメソッド内に記述します。
 URL url = new URL("http://localhost:8080/web/get?key=value");
 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
 urlConnection.setRequestMethod("GET");
 int statusCode = urlConnection.getResponseCode();
 if (statusCode ==  200) {
      InputStream it = new BufferedInputStream(urlConnection.getInputStream());
      InputStreamReader read = new InputStreamReader(it);
      BufferedReader buff = new BufferedReader(read);
      StringBuilder dta = new StringBuilder();
      String chunks ;
      while((chunks = buff.readLine()) != null)
      {
         dta.append(chunks);
      }
 }
 else
 {
     //Handle else
 }私にとって、最も簡単な方法はRetrofit2というライブラリを使用することです
リクエストメソッド、パラメーターを含むインターフェイスを作成するだけで、リクエストごとにカスタムヘッダーを作成できます。
    public interface MyService {
      @GET("users/{user}/repos")
      Call<List<Repo>> listRepos(@Path("user") String user);
      @GET("user")
      Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);
      @POST("users/new")
      Call<User> createUser(@Body User user);
      @FormUrlEncoded
      @POST("user/edit")
      Call<User> updateUser(@Field("first_name") String first, 
                            @Field("last_name") String last);
      @Multipart
      @PUT("user/photo")
      Call<User> updateUser(@Part("photo") RequestBody photo, 
                            @Part("description") RequestBody description);
      @Headers({
        "Accept: application/vnd.github.v3.full+json",
        "User-Agent: Retrofit-Sample-App"
      })
      @GET("users/{username}")
      Call<User> getUser(@Path("username") String username);    
    }そして最高は、エンキューメソッドを使用して非同期で簡単に行うことができます
最近のAndroidとJavaで非常に人気のあるHTTPクライアントであるOkHttpを使用してリクエストを実行する方法については、どの回答でも説明していなかったので、簡単な例を示します。
//get an instance of the client
OkHttpClient client = new OkHttpClient();
//add parameters
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
urlBuilder.addQueryParameter("query", "stack-overflow");
String url = urlBuilder.build().toString();
//build the request
Request request = new Request.Builder().url(url).build();
//execute
Response response = client.newCall(request).execute();このライブラリの明らかな利点は、低レベルの詳細から私たちを抽象化し、それらと対話するためのよりフレンドリーで安全な方法を提供することです。構文も単純化されており、素晴らしいコードを書くことができます。