我處處搜索但我找不到答案,有沒有辦法發出簡單的HTTP請求? 我想在個人某個網站上請求PHP頁面/腳本,但我不想顯示該網頁。 html
若是可能的話我甚至想在後臺(在BroadcastReceiver中)這樣作 java
我使用Gson lib爲web服務建立了這個URL: android
客戶: git
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; }
private String getToServer(String service) throws IOException { HttpGet httpget = new HttpGet(service); ResponseHandler<String> responseHandler = new BasicResponseHandler(); return new DefaultHttpClient().execute(httpget, responseHandler); }
問候 github
注意:如今不推薦使用與Android捆綁在一塊兒的Apache HTTP Client,而使用HttpURLConnection 。 有關詳細信息,請參閱Android開發人員博客 。 web
將<uses-permission android:name="android.permission.INTERNET" />
到清單中。 api
而後,您將檢索以下所示的網頁: 網絡
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(); }
我還建議在一個單獨的線程上運行它: ide
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 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); } }
這是一個很是古老的答案。 我絕對不會再推薦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");