publicclassHttpExampleActivityextendsActivity{privatestaticfinalStringDEBUG_TAG="HttpExample";privateEditTexturlText;privateTextViewtextView;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);urlText=(EditText)findViewById(R.id.myUrl);textView=(TextView)findViewById(R.id.myText);}// When user clicks button, calls AsyncTask.// Before attempting to fetch the URL, makes sure that there is a network connection.publicvoidmyClickHandler(Viewview){// Gets the URL from the UI's text field.StringstringUrl=urlText.getText().toString();ConnectivityManagerconnMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfonetworkInfo=connMgr.getActiveNetworkInfo();if(networkInfo!=null&&networkInfo.isConnected()){newDownloadWebpageText().execute(stringUrl);}else{textView.setText("No network connection available.");}}// Uses AsyncTask to create a task away from the main UI thread. This task takes a // URL string and uses it to create an HttpUrlConnection. Once the connection// has been established, the AsyncTask downloads the contents of the webpage as// an InputStream. Finally, the InputStream is converted into a string, which is// displayed in the UI by the AsyncTask's onPostExecute method.privateclassDownloadWebpageTextextendsAsyncTask{@OverrideprotectedStringdoInBackground(String...urls){// params comes from the execute() call: params[0] is the url.try{returndownloadUrl(urls[0]);}catch(IOExceptione){return"Unable to retrieve web page. URL may be invalid.";}}// onPostExecute displays the results of the AsyncTask.@OverrideprotectedvoidonPostExecute(Stringresult){textView.setText(result);}}...}
关于上面那段代码的示例详解,请参考下面:
When users click the button that invokes myClickHandler(), the app passes the specified URL to the AsyncTask subclass DownloadWebpageTask.
The AsyncTask method doInBackground() calls the downloadUrl() method.
The downloadUrl() method takes a URL string as a parameter and uses it to create a URL object.
The URL object is used to establish an HttpURLConnection.
Once the connection has been established, the HttpURLConnection object fetches the web page content as an InputStream.
The InputStream is passed to the readIt() method, which converts the stream to a string.
Finally, the AsyncTask’s onPostExecute() method displays the string in the main activity’s UI.
Connect and Download Data(连接并下载数据)
在执行网络交互的线程里面,你可以使用 HttpURLConnection 来执行一个 GET 类型的操作并下载数据。在你调用 connect()之后,你可以通过调用getInputStream()来得到一个包含数据的InputStream 对象。
// Given a URL, establishes an HttpUrlConnection and retrieves// the web page content as a InputStream, which it returns as// a string.privateStringdownloadUrl(Stringmyurl)throwsIOException{InputStreamis=null;// Only display the first 500 characters of the retrieved// web page content.intlen=500;try{URLurl=newURL(myurl);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setReadTimeout(10000/* milliseconds */);conn.setConnectTimeout(15000/* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);// Starts the queryconn.connect();intresponse=conn.getResponseCode();Log.d(DEBUG_TAG,"The response is: "+response);is=conn.getInputStream();// Convert the InputStream into a stringStringcontentAsString=readIt(is,len);returncontentAsString;// Makes sure that the InputStream is closed after the app is// finished using it.}finally{if(is!=null){is.close();}}}
请注意,getResponseCode() 会返回连接状态码( status code). 这是一种获知额外网络连接信息的有效方式。status code 是 200 则意味着连接成功.
Convert the InputStream to a String(把InputStream的数据转换为String)
// Reads an InputStream and converts it to a String.publicStringreadIt(InputStreamstream,intlen)throwsIOException,UnsupportedEncodingException{Readerreader=null;reader=newInputStreamReader(stream,"UTF-8");char[]buffer=newchar[len];reader.read(buffer);returnnewString(buffer);}