巧用 Android 网络通信技术,在网络上直接传输对象 (2),android 开发入门基础教程
新建一个 Android 工程,命名为 ClientTest 作为客户端工程。这里第一个要确定的就是待传输的对象,我们新建一个 Book 类,代码如下:
package com.test;
import java.io.Serializable;
public class Book implements Serializable {
private String bookName;
private String author;
private double price;
private int pages;
public String getBookName() {return bookName;}
public void setBookName(String bookName) {this.bookName = bookName;}
public String getAuthor() {return author;}
public void setAuthor(String author) {this.author = author;}
public double getPrice() {return price;}
public void setPrice(double price) {this.price = price;}
public int getPages() {return pages;}
public void setPages(int pages) {this.pages = pages;}
}
这个类就是一个简单的 POJO,但是要注意一点,它实现了 Serializable 接口,如果想在网络上传输对象,那么该对象就一定要实现 Serializable 接口。
三
接下来打开或新建 activity_main.xml 作为程序的主布局文件,加入如下代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#000"tools:context=".MainActivity" >
<Buttonandroid:id="@+id/send"
android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="发送"/>
</RelativeLayout>
这个布局里面就是包含了一个按钮,点击这个按钮就去发出网络请求。
接下来打开或新建 MainActivity 作为程序的主 Activity,其中加入如下代码:
public class MainActivity extends Activity implements OnClickLis
tener {
private Button send;
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);send = (Button) findViewById(R.id.send);send.setOnClickListener(this);}
@Overridepublic void onClick(View v) {Book book = new Book();book.setBookName("Android 高级编程");book.setAuthor("Reto Meier");book.setPages(398);book.setPrice(59.00);URL url = null;ObjectOutputStream oos = null;try {url = new URL("http://192.168.1.103:8080/ServerTest/servlet/TestServlet");HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoInput(true);connection.setDoOutput(true);connection.setConnectTimeout(10000);connection.setReadTimeout(10000);connection.setRequestMethod("POST");oos = new ObjectOutputStream(connection.getOutputStream());oos.writeObject(book);InputStreamReader read = new InputStreamReader(connection.getInputStream());BufferedReader br = new BufferedReader(read);String line = "";while ((line = br.readLine()) != null) {Log.d("TAG", "line is " + line);}br.close();connection.disconnect();} catch (Exception e) {e.printStackTrace();} finally {
评论