Wykonaj żądanie HTTP za pomocą Androida
Szukałem wszędzie, ale nie mogłem znaleźć odpowiedzi, czy jest sposób na proste żądanie HTTP? Chcę poprosić o stronę / skrypt PHP na jednej z moich stron, ale nie chcę pokazywać strony.
Jeśli to możliwe, nawet chcę to zrobić w tle (w BroadcastReceiver)
11 answers
UPDATE
To bardzo stara odpowiedź. Zdecydowanie Nie będę już polecał klienta Apache. Zamiast tego użyj albo:Oryginalna Odpowiedź
Po pierwsze, poproś o pozwolenie na dostęp do sieci, Dodaj następujący manifest:
<uses-permission android:name="android.permission.INTERNET" />
Najprostszym sposobem jest użycie klienta http Apache w pakiecie z Androidem:
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());
}
Jeśli chcesz aby działał na osobnym wątku polecam rozszerzenie 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..
}
}
Następnie możesz złożyć wniosek przez:
new RequestTask().execute("http://stackoverflow.com");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-19 21:13:46
Jeśli nie masz wyraźnego powodu, aby wybrać Apache HttpClient, powinieneś preferować java. net. URLConnection. możesz znaleźć wiele przykładów, jak z niego korzystać w Internecie.
Poprawiliśmy również dokumentację Androida od czasu twojego oryginalnego postu: http://developer.android.com/reference/java/net/HttpURLConnection.html
I rozmawialiśmy o kompromisach na oficjalnym blogu: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-22 23:01:04
Uwaga: Klient HTTP Apache w pakiecie z Androidem jest obecnie przestarzały na rzecz HttpURLConnection . Więcej informacji można znaleźć na blogu deweloperów Androida .
Dodaj <uses-permission android:name="android.permission.INTERNET" />
do manifestu.
Wtedy odzyskasz stronę w ten sposób:
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();
}
Proponuję też uruchomić go na osobnym wątku:
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..
}
}
Zobacz Dokumentacja aby uzyskać więcej informacji na temat obsługi odpowiedzi i żądań POST.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-01 17:18:35
Najprostszym sposobem jest użycie Android lib o nazwie
Volley oferuje następujące korzyści:
Automatyczne planowanie żądań sieciowych. Multiple concurrent network połączenia . Przezroczyste buforowanie odpowiedzi dysku i pamięci z standardowa spójność pamięci podręcznej HTTP. Obsługa priorytetyzacji żądań. API żądania anulowania. Możesz anulować pojedyncze żądanie lub możesz ustawia bloki lub zakresy żądań do anulowania. Łatwość Personalizacja, dla przykład, dla retry i backoff. Mocne zamawianie, które ułatwia poprawnie wypełniaj swój UI danymi pobieranymi asynchronicznie z sieć. Narzędzia do debugowania i śledzenia.
Możesz wysłać żądanie http / https tak prosto, jak to:
// 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);
W tym przypadku nie musisz myśleć o "uruchamianiu w tle" lub "używaniu pamięci podręcznej", ponieważ wszystko to zostało już zrobione przez Volley.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 05:08:15
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
Pozdrawiam
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-30 18:07:39
Z wątkiem:
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);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-18 21:12:54
Spójrz na tę niesamowitą nową bibliotekę, która jest dostępna przez gradle:)
Zbuduj.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
Użycie:
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();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-04 00:00:09
Zrobiłem to dla webservice do requerst na URL, używając GSON lib:
Klient:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-05 13:51:02
To jest nowy kod dla żądania HTTP Get / POST w Androidzie. HTTPClient
jest depricated i może nie być dostępny, Jak to było w moim przypadku.
Najpierw dodaj dwie zależności W build."gradle": {]}
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
Następnie wpisz ten kod w ASyncTask
w metodzie 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
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-29 19:34:24
Dla mnie najprostszym sposobem jest użycie biblioteki o nazwie Retrofit2
Musimy tylko stworzyć interfejs, który będzie zawierał naszą metodę żądania, parametry, a także możemy stworzyć niestandardowy nagłówek dla każdego żądania:
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);
}
A najlepsze jest to, że możemy to zrobić asynchronicznie łatwo używając metody enqueue
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-02 20:49:26
Ponieważ żadna z odpowiedzi nie opisała sposobu wykonywania żądań za pomocą OkHttp , który jest obecnie bardzo popularnym klientem http dla Androida i Javy w ogóle, podam prosty przykład:
//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();
Wyraźną zaletą tej biblioteki jest to, że pobiera nas od niektórych szczegółów niskiego poziomu, zapewniając bardziej przyjazne i bezpieczne sposoby interakcji z nimi. Składnia jest również uproszczona i pozwala na pisanie ładnego kodu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-11 18:59:43