這是一個android前臺向服務端網站請求少許數據的小例子。html
首先設計好服務端,再來寫安卓前端。前端
一:服務端java
Internet文件的代碼:android
package android; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Internet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動生成的方法存根 //super.doGet(req, resp); resp.setContentType("text/html;charset=utf-8"); PrintWriter print=resp.getWriter(); print.println("你好!");//客戶端能夠接收穫得,本網頁顯示 print.println("上海!"); print.flush();//flush()不能夠少 System.out.println("瓜瓜!");//客戶端接收不到,本網頁不顯示,輸出在控制檯 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自動生成的方法存根 super.doPost(req, resp); } @Override protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { // TODO 自動生成的方法存根 super.service(arg0, arg1); } @Override public void init() throws ServletException { // TODO 自動生成的方法存根 super.init(); } }
配置的web.xmlweb
<servlet> <servlet-name>a</servlet-name> <servlet-class>android.Internet</servlet-class> </servlet> <servlet-mapping> <servlet-name>a</servlet-name> <url-pattern>/b</url-pattern> </servlet-mapping>
訪問路徑:服務器
至此服務端的書寫已經成功,接下來開始安卓端的書寫。網絡
二:安卓手機端併發
activity_main.xml只有一個控件app
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" " android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout>
主線程MainActivity.javaide
import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import com.internethttp.R; public class MainActivity extends ActionBarActivity { String url="http://ly-and-tl.uicp.cn:42696/AndroidServer/b";//服務端的servlet頁面網址,在web.xml頁面中已配置 TextView tv; Handler handler; @SuppressLint("HandlerLeak") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView) findViewById(R.id.textView); handler=new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what==3){//後臺發送消息切換回主線程後的處理 CharSequence ss=(CharSequence)msg.obj;//拿到消息的包裹信息 System.out.println(ss+"MainActivity"); if(ss!=null){ tv.setText(ss);//只能在主線程更新UI } } } }; new HttpThread(url,handler).start(); } }
子線程HttpThread.java
public class HttpThread extends Thread { String url; Handler handler; HttpThread(String url,Handler hand){ this.url=url; handler=hand; } @Override public void run() {//向後臺請求數據 // TODO Auto-generated method stub //super.run(); URL httpUrl; try { httpUrl=new URL(url); HttpURLConnection conn=(HttpURLConnection)(httpUrl.openConnection()); //打開服務端的某個頁面連接就至關於自動調用doGet()方法 conn.setReadTimeout(5000); //5000秒內不返回就報錯 conn.setRequestMethod("GET"); //bufferReader適合中文類,HttpURLConnection的getInputStream()方法返回一個InputStream對象, //InputStreamReader接收InputStream對象能實例化一個InputStreamReader, //bufferedReader能接收一個InputStreamReader對象實例化本身 BufferedReader buff=new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb=new StringBuffer(); String str; while((str=buff.readLine())!=null){ //readLine()返回String對象,從後臺拿到數據存到String對象 sb.append(str); } System.out.println(sb+"HttpThread"); Message msg=handler.obtainMessage(3); msg.obj=sb; handler.sendMessage(msg); //發送到主線程,馬上切換線程 } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
最後別忘了對網絡權限的設置。
運行效果: