373

どこでも検索しましたが、答えが見つかりませんでした。簡単なHTTPリクエストを作成する方法はありますか?自分のWebサイトの1つでPHPページ/スクリプトを要求したいのですが、Webページを表示したくありません。

可能であれば、バックグラウンドで(BroadcastReceiverで)実行したい場合もあります

4

12 に答える 12

490

アップデート

これは非常に古い答えです。私は間違いなくApacheのクライアントをもうお勧めしません。代わりに、次のいずれかを使用してください。

元の回答

まず、ネットワークへのアクセス許可をリクエストし、マニフェストに以下を追加します。

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

次に、AndroidにバンドルされているApachehttpクライアントを使用するのが最も簡単な方法です。

    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");
于 2010-08-17T19:11:11.840 に答える
68

Apache HttpClientを選択する明確な理由がない限り、java.net.URLConnectionを選択する必要があります。Web上でそれを使用する方法の例をたくさん見つけることができます。

また、元の投稿以降、Androidのドキュメントも改善されています:http://developer.android.com/reference/java/net/HttpURLConnection.html

公式ブログでトレードオフについて話しました:http://android-developers.blogspot.com/2011/09/androids-http-clients.html

于 2010-08-18T05:55:59.937 に答える
47

注: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要求の詳細については、ドキュメントを参照してください。

于 2015-06-30T20:54:20.940 に答える
14

最も簡単な方法は、Volleyと呼ばれるAndroidライブラリを使用することです

ボレーには次の利点があります。

ネットワーク要求の自動スケジューリング。複数の同時ネットワーク接続。標準のHTTPキャッシュコヒーレンスを使用した透過的なディスクおよびメモリ応答キャッシング。リクエストの優先順位付けのサポート。キャンセルリクエストAPI。1つのリクエストをキャンセルすることも、キャンセルするリクエストのブロックまたはスコープを設定することもできます。再試行やバックオフなどのカスタマイズのしやすさ。ネットワークから非同期にフェッチされたデータを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によってすでに実行されているため、「バックグラウンドで実行する」または「キャッシュを使用する」ことを自分で検討する必要はありません。

于 2017-05-27T05:08:15.493 に答える
8

上記のようにボレーを使用します。以下を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クライアントに置き換わるもので、非常にシンプルです。

于 2019-09-28T09:22:29.580 に答える
6
private String getToServer(String service) throws IOException {
    HttpGet httpget = new HttpGet(service);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    return new DefaultHttpClient().execute(httpget, responseHandler);

}

よろしく

于 2014-07-30T18:07:39.610 に答える
5

スレッド付き:

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);
    }
}
于 2010-08-17T19:03:32.707 に答える
5

現在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();

このライブラリの明らかな利点は、いくつかの低レベルの詳細から私たちを抽象化し、それらと対話するためのよりフレンドリーで安全な方法を提供することです。構文も単純化されており、優れたコードを記述できます。

于 2018-06-11T18:59:43.527 に答える
4

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;
}
于 2014-06-05T13:51:02.193 に答える
4

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();

https://github.com/erf/http-request

于 2016-05-04T00:00:09.657 に答える
2

これは、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
 }
于 2016-03-29T19:34:24.220 に答える
1

私にとって最も簡単な方法は、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);    

    }

そして最良の方法は、enqueueメソッドを使用して非同期で簡単に実行できることです

于 2017-04-02T20:49:26.783 に答える