当前位置:首页 > CN2资讯 > 正文内容

android 快速服务器 android链接服务器

1天前CN2资讯



用了一个礼拜的时间研究了android连接服务器的大体流程。连接服务器有两种办法,一种是使用java类HttpURLConnection,另一个是使用apache的类HttpClient,看了android的官方文档,在安卓2.3以后建议使用HttpURLConnection进行开发。以下为本人亲测实例,希望对大家有帮助,也作为以后再次使用网络连接服务器的一个参考,如有不对之处,尽请指正,感激不尽。



android客户端: 首先书写一个HttpUtil类,封装了连接、请求服务器所需的post方法和get方法,因为get方法代码比较简单,在此就略过了,代码如下:


public class HttpUtil { public static final String BASE_URL = "http://xxx.xxx.xxx.xxx:8080/TestAndroidServlet/android/"; public static HttpURLConnection conn; public static String PostFromWebByHttpURLConnection(String strUrl, Map<String, String> map) { String result = ""; try { URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); // 设置是否从httpUrlConnection读入,默认情况下是true; conn.setDoInput(true); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true, 默认情况下是false; conn.setDoOutput(true); // 设定请求的方法为"POST",默认是GET conn.setRequestMethod("POST"); // 设置超时 conn.setConnectTimeout(3000); conn.setReadTimeout(4000); // Post 请求不能使用缓存 conn.setUseCaches(false); // 是否连接遵循重定向 conn.setInstanceFollowRedirects(true); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, conn.connect(); String user = map.get("user"); DataOutputStream dop = new DataOutputStream(conn.getOutputStream()); //用此方法向服务器端发送数据 dop.writeBytes("user="+URLEncoder.encode(user, "utf-8")); dop.flush(); dop.close(); //接收数据 InputStream in = conn.getInputStream(); InputStreamReader inStream = new InputStreamReader(in); BufferedReader buffer = new BufferedReader(inStream); String strLine = null; while ((strLine = buffer.readLine()) != null) { result += strLine; } return result; } catch (IOException ex) { ex.printStackTrace(); return null; } } }不要忘记给app添加访问网络的权限



<uses-permission android:name="android.permission.INTERNET"/>主界面程序:



public class Login extends Activity { // 定义界面中文本框 EditText etName; // 定义界面中按钮 Button bnLogin; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); // 获取界面中编辑框 etName = (EditText) findViewById(.userEditText); // 获取界面中的按钮 bnLogin = (Button) findViewById(.bnLogin); bnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 如果登录成功 if (login()) { Toast.makeText(Login.this, "连接服务器成功", Toast.LENGTH_LONG).show(); } } }); } private boolean login() { // 获取用户输入的用户名 String username = etName.getText().toString(); String result; try { result = query(username); if ("成功".equals(result.trim())) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } // 定义发送请求的方法 private String query(String username) throws Exception { // 使用Map封装请求参数 Map<String, String> map = new HashMap<String, String>(); map.put("user", username); // 定义发送请求的URL String url = HttpUtil.BASE_URL + "login.jsp"; // 发送请求 return HttpUtil.PostFromWebByHttpURLConnection(url, map); } }xml布局文件:



<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http:///apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1"> <TableRow> <TextView android:text="@string/user_name" android:id="@+id/TextView" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/userEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> </TableRow> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" > <Button android:id="@+id/bnLogin" android:text="@string/login" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> </TableLayout>捎带也把服务器端的代码也写上,使用serlvet3.0的新特性,以注释的方式引入jsp,同时不要忘记引入servlet-api.jar。@WebServlet(urlPatterns = "/android/login.jsp") public class LoginServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String user = request.getParameter("user"); System.out.println(user); response.setContentType("text/html; charset=utf-8"); // 登录成功 if (user.equals("user")) { response.getWriter().println("成功"); } } }






    你可能想看:

    扫描二维码推送至手机访问。

    版权声明:本文由皇冠云发布,如需转载请注明出处。

    本文链接:https://www.idchg.com/info/23239.html

    分享给朋友:

    “android 快速服务器 android链接服务器” 的相关文章

    ZGOVPS优惠码使用指南:如何享受高性能VPS服务的优惠

    ZGOVPS是一家在VPS服务领域备受瞩目的品牌。作为一个提供高性能虚拟专用服务器的商家,它在业内以性价比高、网络稳定和良好口碑而受到广泛欢迎。我在使用ZGOVPS的过程中,深刻感受到了它对客户需求的敏锐把握和优质服务的承诺。 从公司的背景来看,ZGOVPS专注于为全球用户提供专业的VPS解决方案,...

    全面指南:在Linux上使用dd命令安装Windows系统的教程

    在当今的技术环境中,许多用户都希望能够在Linux系统上安装Windows。这不仅能帮助开发者和测试人员多平台间的快速切换,还能让个人用户享受到两个操作系统的优点。dd命令成为了实现这一目标的一个重要工具,通过它,可以将Windows操作系统的映像文件直接写入到一个虚拟专用服务器上。这篇教程将为你提...

    VPS搭建:从选择提供商到后续管理的全面指南

    什么是VPS搭建? 了解VPS搭建的第一步是弄清楚VPS的定义。VPS,全称为虚拟专用服务器,是将一个物理服务器划分成多个独立的虚拟服务器。每个VPS都具有自己的操作系统和资源,能够像独立服务器一样运行各种应用程序。这种方式提供了更高的灵活性和可控性,相比共享主机来说,用户能够自主安装软件,配置环境...

    选择最佳香港VPS大带宽服务的全面指南,助你无忧搭建在线业务

    在如今这个信息高速发展的时代,选择适合的VPS服务显得尤为重要。特别是香港VPS大带宽服务,以其独特的优势吸引了越来越多的用户。对于想要进行国际业务、网站托管或是搭建游戏服务器的用户来说,香港VPS大带宽服务绝对是个不错的选择。 香港VPS大带宽的优势显而易见。一个显著的特点是无需备案,这意味着用户...

    50kvm VPS主机服务:最优性价比与便捷选择

    50kvm是一个备受推崇的VPS主机服务品牌,它因其卓越的性价比和高效的速度而广受欢迎。这个品牌提供多种不同 유형的VPS解决方案,覆盖了从美国到亚洲的多个数据中心。特别是美国波特兰的Cera (NCP)和洛杉矶C3、Cera CN2 GIA等产品,都是非常值得关注的选择。 在我了解50kvm的过程...

    波测评分析及其在医疗与教育领域的重要性

    波测评的定义与重要性 波测评是一种重要的技术手段,专注于评估波动的特性和行为。我发现,这种测评方法在多个行业中都扮演了至关重要的角色,比如医疗、工业和电力等领域。以脑波测评为例,它不仅可以帮助医生了解病人的大脑状态,还能在教育领域评估学习能力。这些应用展示了波测评技术在科学与技术进步中的不可或缺性。...