用android做一个HTTP请求
我到处search,但我找不到我的答案,有没有办法做一个简单的HTTP请求? 我想在我的一个网站上申请一个PHP页面/脚本,但是我不想显示这个网页。
如果可能的话,我甚至想在后台做(在BroadcastReceiver中)
UPDATE
这是一个非常古老的答案。 我绝对不会推荐Apache的客户端了。 考虑使用HttpUrlConnection或OkHttp来代替。
UPDATE
首先,请求访问networking的权限,添加以下到您的清单:
<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()); }
如果你想让它在单独的线程上运行,我build议扩展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");
除非你有明确的理由selectApache HttpClient,否则你应该更喜欢java.net.URLConnection。 你可以find很多关于如何在networking上使用它的例子。
我们还改进了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" />
到清单中。
然后你会像这样检索一个网页:
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(); } }
我也build议在单独的线程上运行它:
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请求的更多信息,请参阅文档 。
private String getToServer(String service) throws IOException { HttpGet httpget = new HttpGet(service); ResponseHandler<String> responseHandler = new BasicResponseHandler(); return new DefaultHttpClient().execute(httpget, responseHandler); }
问候
用线程:
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); } }
看看这个可怕的新库,通过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的Android库
Volley提供以下好处:
自动调度networking请求。 多个并发networking连接 。 标准HTTPcaching一致性的透明磁盘和内存响应caching。 支持请求优先级。 取消请求API。 您可以取消单个请求,也可以设置要取消的请求的范围或范围。 易于定制,例如重试和退避。 强大的sorting使得使用从networkingasynchronous获取的数据可以很容易地正确填充您的用户界面。 debugging和跟踪工具。
您可以像这样简单地发送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);
在这种情况下,您不必考虑“自己在后台运行”或“使用caching”,因为所有这些已经由Volley完成了。
我做了这个web服务来请求URL的使用Gson lib:
客户:
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; }
这是android中HTTP Get / POST请求的新代码。 HTTPClient
是depricated,可能不会像我的情况。
首先在build.gradle中添加两个依赖项:
compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'org.apache.httpcomponents:httpclient:4.5'
然后用doBackground
方法在ASyncTask
中编写这段代码。
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的库
我们只需要创build一个包含我们的请求方法和参数的接口,并且我们还可以为每个请求创build自定义头:
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); }
而最好的是,我们可以使用入队方法asynchronous轻松地完成