Android实现简易联网交互
来源:互联网 发布:java中的多态是什么 编辑:程序博客网 时间:2024/06/01 09:26
Android实现简易联网交互
作者:ftyxt,转载请注明http://blog.csdn.net/qq_37624896/article/details/78592704
(≧∇≦)/,本demo使用http协议实现android客户端与服务器的一个简单交互功能(验证账号密码):
一、客户端代码(Android Studio)
首先需要写一个NetUtil类,此类实现消息的联网发送与接收:
import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class NetUtil { /** * 发送http请求 * @param username * @param password */ public static String loginOfGet(String username,String password){ HttpURLConnection conn=null; String myurl = "http://120.27.209.207:8080/Server/Service?"; try { String data="Message="+username+"&password="+password; URL url=new URL(myurl+data); conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); conn.setReadTimeout(5000); conn.connect(); int code=conn.getResponseCode(); if(code==200){ InputStream is=conn.getInputStream(); String state=getStringFromInputStream(is); return state; } } catch (Exception e) { e.printStackTrace(); }finally{ if(conn!=null){ conn.disconnect(); } } return null; } /** * 根据输入流返回一个字符串 * @param is * @throws Exception */ private static String getStringFromInputStream(InputStream is) throws Exception{ ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buff=new byte[1024]; int len=-1; while((len=is.read(buff))!=-1){ baos.write(buff, 0, len); } is.close(); String html=baos.toString(); baos.close(); return html; }}
访问的myurl需要根据自己实际服务器所用公网IP地址(或与客户端同一局域网下的IP地址)和项目名称路径来确定。8080为Service项目所搭载的tomcat软件开辟的端口。
有了这个自定义类后面就比较简单了,附上MainActivity代码:
import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import android.widget.EditText;public class MainActivity extends AppCompatActivity { public Button bt; public EditText et_username; public EditText et_password; public TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button)findViewById(R.id.button); tv = (TextView)findViewById(R.id.textView); et_username = (EditText)findViewById(R.id.username); et_password = (EditText)findViewById(R.id.password); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { final String username = et_username.getText().toString(); final String password = et_password.getText().toString(); @Override public void run() { //访问网络要在子线程中实现,使用get取数 final String state=NetUtil.loginOfGet(username,password); //执行在主线程上 runOnUiThread(new Runnable() { public void run() { //就是在主线程上操作,弹出结果 if(state.equals("success")){ tv.setText(state); }else{ Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show(); } } }); } }).start(); } }); }}
还有layout文件和Manifest文件:
layout文件:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:id="@+id/textView" android:layout_marginBottom="49dp" android:layout_above="@+id/button" android:layout_centerHorizontal="true" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="confirm" tools:layout_editor_absoluteX="148dp" tools:layout_editor_absoluteY="153dp" android:layout_marginBottom="100dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /> <EditText android:id="@+id/username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="72dp" android:ems="10" android:inputType="textPersonName" android:hint="username" /> <EditText android:id="@+id/password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:hint="password" android:layout_below="@+id/username" android:layout_alignLeft="@+id/username" android:layout_alignStart="@+id/username" android:layout_marginTop="58dp" /></RelativeLayout>
Manifest文件,申请联网权限:
<uses-permission android:name="android.permission.INTERNET"/>
二、服务端代码(Eclipse)
我们服务器只是处理简单逻辑并返回值,所以不需要和复杂。
服务器端代码:
import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/Service")public class Service extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Service() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String username = request.getParameter("username"); String password = request.getParameter("password"); if(username.equals("123")&&password.equals("789")){//账号:123 密码:789 response.setContentType("text/html;charset=UTF-8"); response.getWriter().println("success"); }else{ response.setContentType("text/html;charset=UTF-8"); response.getWriter().println("failed"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }}
将服务器代码打包成web项目挂载到tomcat上,服务器就启动啦。
使用Android手机客户端也访问成功 (ಡωಡ)hiahiahia
看似麻烦的联网功能,其实并不复杂。实现更多,更加复杂的联网交互处理也可以在这个demo的基础上发展来实现,所以掌握实现基础联网功能的方法是非常有必要的(ง •̀_•́)ง
个人原创:ftyxt
阅读全文
0 0
- Android实现简易联网交互
- Android Service+Socket 联网交互
- Android Service+Socket 联网交互
- Android Service+Socket 联网交互
- 使用 Android 实现联网
- 使用 Android 实现联网
- Android 实现联网
- 使用 Android 实现联网
- android 游戏实现联网
- python3嵌入mysql实现简易交互界面
- Android 与 H5-JS 简易交互
- Android简易闹钟实现
- Android 简易计算器实现
- Android 简易刮刮卡实现
- 简易物联网
- 应用程序和驱动的简易交互方式的实现
- 搭建简易ZK框架并实现简单交互
- Android:简易弹幕效果实现
- 网络编程:网络基础
- lua math库
- 探究Python生成随机字符串
- B树简单理解
- 剑指offer 反转链表
- Android实现简易联网交互
- jndi
- Hivesql里的limit使用误区
- 关于Oracle检索字段值小数点前面0不显示问题
- android 自定义view绘制流程
- Nginx配置和启动
- 在macOS上使用Python+MySQL连接Tushare,进行股票数据下载
- 瑟瑟发抖……
- 使用vim并预览markdown