Android开发中如何使用Java与服务器进行交互? (android java 服务器)
随着移动互联网的快速发展,越来越多的应用程序需要跟服务器进行交互。这就要求开发者要掌握如何使用Java与服务器进行交互,以便开发出更加完善的Android应用。本文将详细介绍Android开发中如何使用Java与服务器进行交互的方法和技巧。
一、什么是Java与服务器交互?
Java与服务器交互,就是android客户端与服务器端进行数据交换的过程。在Android应用中,客户端需要发送请求到服务器,服务器将请求解析后执行相应的业务逻辑,并将结果返回给客户端。该过程一般分为两个部分:Android客户端的请求和服务器端的响应。
二、Java与服务器交互的方式
Android开发中,可以使用多种方式与服务器进行交互,包括Soap、Http、Socket和XML等。下面将分别介绍这几种交互方式。
1. Soap
Soap是指“简单对象访问协议”,是一种Web服务协议。使用Soap协议的好处是可以跨平台使用,也就是说可以在任何操作系统上运行,包括Windows、Linux和Mac等操作系统。
在Android开发中,如果需要使用Soap协议与服务器进行交互,可以使用第三方开源库Ksoap2-android。Ksoap2-android提供了简单易用的API,支持Soap1.1和Soap1.2版本,开发者可以根据自己的具体业务需求选择相应的版本。
2. Http
Http是指“超文本传输协议”,是一种应用层协议,主要用于传输超媒体文档(例如HTML)。在Android应用中,我们通常使用Http协议进行数据交换,包括用户登录、获取数据、上传图片和文件等操作。
Android开发中,可以使用HttpURLConnection和HttpClient两种方式访问服务器。其中HttpURLConnection是Android系统自带的API,HttpClient是Apache提供的开源库。
3. Socket
Socket是指“套接字”,是一种支持TCP/IP协议的网络通信方式。在Android应用中,Socket主要用于实时通信,例如聊天室应用程序等。
使用Socket进行网络通信时,需要注意数据加密和传输的稳定性。如果需要进行数据加密,可以使用SSL协议。如果需要保证传输的稳定性,可以使用Heartbeat等机制来监测数据传输的状态。
4. XML
XML是指“可扩展标记语言”,是一种用于描述数据格式的标记语言。在Android应用中,XML主要用于数据的存储和传输,例如使用XmlSerializer解析XML数据。
使用XML进行数据存储和传输时,需要注意处理数据的转义和转码。如果数据内容涉及HTML的特殊字符,比如””等,需要进行转义;如果传输的数据需要进行编码,比如中文字符集GB2312,需要进行转码,确保数据的完整性和正确性。
三、Android开发中Java与服务器交互的流程
使用Java与服务器进行交互需要经过以下四个步骤:
1. 创建URL对象。首先需要创建一个URL对象,该对象可以指定请求的URL地址和参数。
2. 打开URL连接。通过URL对象打开一个HttpURLConnection连接或Socket连接,启动网络连接,与服务器建立通信。
3. 发送请求。在连接成功后,发送请求数据给服务器。具体的请求数据格式和内容,需要根据业务逻辑和服务端协议来确定,例如字段名称、字段类型、请求方式等。
4. 处理响应。服务器处理请求后,将响应数据发送给客户端。客户端接收响应数据后,对于成功响应和错误响应要进行对应的处理。
四、Java与服务器交互的开发技巧
在Android开发中,使用Java与服务器进行交互时需要注意以下几个开发技巧:
1. 网络权限。在AndroidManifest.xml文件中需要添加网络权限,否则无法进行网络通信。
2. 处理错误响应。如果发送的请求出现错误,例如参数错误、网络故障等,需要对错误响应进行处理,给用户及时反馈。
3. 异步处理。由于网络请求是一项耗时操作,Android应用中需要在异步线程中完成网络操作,防止UI线程被阻塞。
4. 缓存处理。在进行网络请求时,可以使用缓存机制加速网络访问速度,提高用户体验。
五、
相关问题拓展阅读:
如何在Android源码中加入Java层系统服务
把java工程中要用到的类打个jar包,放在android项目中
1. 在android/app/目录下创建接口文件IServiceTest.aidl
package android.app;
oneway interface IServiceTest
{
void show();
}
2. 在Android.mk文槐态件中的变量LOCAL_SRC_FILES中加入core/java/android/app/IServiceTest.aidl
如果要在sdk中发布这个服务猜明穗就在变量aidl_files中加入一样的路径。
3. 通过aidl编译器编译IServiceTest.aidl,会生成一个IServiceTest.java文件。
4. 创建服务类ServiceTestSerice
class ServiceTestSerice extends IServiceTest.Stub{
private static final String TAG = “ServiceTestSerice”;
Context mContext;
public ServiceTestSerice(Context context){
mContext = context;
}
public void show() throws RemoteException {
System.out.println(“My ServiceTestSerice”);
}
}
.5. 注册服务
Java系统服务在ServerThread类的run()方法中生成并注册到android平台,生成ServiceTestSerice实例对象,通过ServiceManager的addService方法将服务注册到系统中穗卜。
try{
serviceTestSerice = new ServiceTestSerice(context);
ServiceManager.addService(Context.SERVICE_TEST, serviceTestSerice);
} catch (Throwable t) {
}
ServiceTestSerice serviceTestSerice;
以上代码在ServerThread类的run()方法中。
在Context类中加入:
public static final StringSERVICE_TEST = “servicetest”
ServiceTestManager sServiceTestManager;
6. 使用系统服务
编写一个ServiceTestManager类,为包装类。
public class ServiceTestManager{
private final IServiceTest mService;
ServiceTestManager(IServiceTest service){
mService = service;
}
public void test(){
try{
mService. show()
} catch (RemoteException ex){
}
}
}
7 提供应用层开发接口
在ContextImpl类中的getSystemService()方法中加入如下代码:
else if (SERVICE_TEST.equals(name)){
return getServiceTestManager();
}
private ServiceTestManager getServiceTestManager(){
synchronized(sSync) {
if (sServiceTestManager == null){
IBinder b = ServiceManager.getService(SERVICE_TEST);
IServiceTest service = IServiceTest.Stub.asInterface(b);
sServiceTestManager = new ServiceTestManager(service);
}
}
调用过程如下:
ServiceTestManager manager= (ServiceTestManager) getSystemService(Context. SERVICE_TEST);
manager.show();
8. 测试
make
make update-api 更新current.xml文件
生成system.imz文件,放到/platform/android-20/images/目录下,
adb shell
service list
求教app保持登录,java服务器和android客户端双方各要做什么
app保持辩渗登录,服务器用session记录用户登录信息就好了
服务器不需姿脊要做什么,就是app上,每次请求需要用同一个cookie
因为session ID是服务器回写在cookie中的
app每次请求都用同一个cookie,就可以实现登迹灶渗录保持了
双向要做一个heartbeat
在Android端使用socket传输图片到java服务器,求源代码
/**
* 思想:
1.直接将所有数据安装字节数组发送
2.对象序列化方式
*/
/**
* thread方式
*
* @author Administrator
*/
public class TestSocketActivity4 extends Activity {
private static final int FINISH = 0;
private Button send = null;
private TextView info = null;
private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FINISH:
String result = msg.obj.toString(); // 取出数据
if (“true”.equals(result)) {
TestSocketActivity4.this.info.setText(“操作成功!”);
} else {
TestSocketActivity4.this.info.setText(“操作失败!”);
滚悄 }
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads().detectDiskWrites().detectNetwork()
// .penaltyLog().build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
// .penaltyLog().penaltyDeath().build());
this.send = (Button) super.findViewById(R.id.send);
this.info = (TextView) super.findViewById(R.id.info);
this.send.setOnClickListener(new SendOnClickListener());
}
private class SendOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
new Thread(new Runnable() {
@Override
public void run() {
try {
//1:
Socket client = new Socket(“192.168.1.165”, 9898);
//2:
ObjectOutputStream oos = new ObjectOutputStream(
client.getOutputStream());
//3:
UploadFile myFile = SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);// 写文件对象
// oos.writeObject(null);// 避免EOFException
磨备森 oos.close();
BufferedReader buf = new BufferedReader(
new InputStreamReader(client
.getInputStream())); // 读取返回的数据
String str = buf.readLine(); // 读取数据
Message msg = TestSocketActivity4.this.myHandler
.obtainMessage(FINISH, str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
瞎亩 client.close();
} catch (Exception e) {
Log.i(“UploadFile”, e.getMessage());
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private UploadFile getUploadFile() throws Exception { // 包装了传送数据
UploadFile myFile = new UploadFile();
myFile.setTitle(“tangcco安卓之Socket的通信”); // 设置标题
myFile.setMimeType(“image/png”); // 图片的类型
File file = new File(Environment.getExternalStorageDirectory()
.toString()
+ File.separator
+ “Pictures”
+ File.separator
+ “b.png”);
InputStream input = null;
try {
input = new FileInputStream(file); // 从文件中读取
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte data = new byte;
int len = 0;
while ((len = input.read(data)) != -1) {
bos.write(data, 0, len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt(“png”);
} catch (Exception e) {
throw e;
} finally {
input.close();
}
return myFile;
}
}
}
public class UploadFile implements Serializable {
private String title;
private byte contentData;
private String mimeType;
private long contentLength;
private String ext;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public byte getContentData() {
return contentData;
}
public void setContentData(byte contentData) {
this.contentData = contentData;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
}
下边是服务端
public class Main4 {
public static void main(String args) throws Exception {
ServerSocket server = new ServerSocket(9898); // 服务器端端口
System.out.println(“服务启动……………………”);
boolean flag = true; // 定义标记,可以一直死循环
while (flag) { // 通过标记判断循环
new Thread(new ServerThreadUtil(server.accept())).start(); // 启动线程
}
server.close(); // 关闭服务器
}
}
public class ServerThreadUtil implements Runnable {
private static final String DIRPATH = “D:” + File.separator + “myfile”
+ File.separator; // 目录路径
private Socket client = null;
private UploadFile upload = null;
public ServerThreadUtil(Socket client) {
this.client = client;
System.out.println(“新的客户端连接…”);
}
@Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream()); // 反序列化
this.upload = (UploadFile) ois.readObject(); // 读取对象//UploadFile需要和客户端传递过来的包名类名相同,如果不同则会报异常
System.out.println(“文件标题:” + this.upload.getTitle());
System.out.println(“文件类型:” + this.upload.getMimeType());
System.out.println(“文件大小:” + this.upload.getContentLength());
PrintStream out = new PrintStream(this.client.getOutputStream());// BufferedWriter
out.print(this.saveFile());//返回响应
//BufferedWriter writer = null;
//writer.write(“”);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
this.client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean saveFile() throws Exception { // 负责文件内容的保存
/**
* java.util.UUID.randomUUID():
* UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。 UUID(Universally
* Unique Identifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
* 是由一个十六位的数字组成
* ,表现出来的形式。由以下几部分的组合:当前日期和时间(UUID的之一个部分与时间有关,如果你在生成一个UUID之后,
* 过几秒又生成一个UUID,
* 则之一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得
* ),UUID的唯一缺陷在于生成的结果串会比较长,字符串长度为36。
*
* UUID.randomUUID().toString()是java JDK提供的一个自动生成主键的方法。 UUID(Universally
* Unique Identifier)全局唯一标识符, 是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,
* 是由一个十六位的数字组成,表现出来的形式
*/
File file = new File(DIRPATH + UUID.randomUUID() + “.”
+ this.upload.getExt());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(this.upload.getContentData());
return true;
} catch (Exception e) {
throw e;
} finally {
output.close();
}
}
}
public class UploadFile implements Serializable {
private String title;
private byte contentData;
private String mimeType;
private long contentLength;
private String ext;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public byte getContentData() {
return contentData;
}
public void setContentData(byte contentData) {
this.contentData = contentData;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
}
这是服务端代码
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server01 {
public static void main(String args) {
try {
ServerSocket server = new ServerSocket(30000);
Socket socket = server.accept();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(“C:/sunnyTest/picture/衫薯cat01.jpg”);
int size = fis.available();
System.out.println(“size = “+size);
byte data = new byte;
fis.read(data);
dos.writeInt(size);
dos.write(data);
dos.flush();
dos.close();
fis.close();
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这吵塌宏里是客户端代码
import com.login.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class TestActivity extends Activity {
private ImageView imageView = null;
private Bitmap bmp = null;
private ImageView imageView02;
private Bitmap bmp02;
private Button button02;
private String uploadFile=”/mnt/升册sdcard/qt.png”;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
imageView = (ImageView) findViewById(R.id.image01);
Button btn = (Button) findViewById(R.id.Button01);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Socket socket = null;
try {
socket = new Socket(“192.168.1.203”, 30000);
DataInputStream dataInput = new DataInputStream(socket.getInputStream());
int size = dataInput.readInt();
byte data = new byte;
int len = 0;
while (len “+bytes);
out.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
android java 服务器的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于android java 服务器,Android开发中如何使用Java与服务器进行交互?,如何在Android源码中加入Java层系统服务,求教app保持登录,java服务器和android客户端双方各要做什么,在Android端使用socket传输图片到java服务器,求源代码的信息别忘了在本站进行查找喔。