【Android开发】采用GET方法进行网络传值

简介:

前两天学习了使用GET方法来进行安卓与WEB的网络传值问题。

 

今天来说一下大概方法。

WEB应用

在这里,我只建立一个简单的Servlet,用来接收安卓端发来的信息。

package deu.hpu.servlet;
 
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 ManagerServlet extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        String title=request.getParameter("title");
        title=new String(title.getBytes("ISO8859-1"),"UTF-8");
        String timelength=request.getParameter("timelength");
        timelength=new String(timelength.getBytes("ISO8859-1"),"UTF-8");
        System.out.println("视频名称"+title);
        System.out.println("时长"+timelength);
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
 doGet(request,response);
}
 
}


 

安卓客户端

在这里,我要建立一个输入框界面,让用户吧数据输入进去,然后我再将数据通过get方式提交。

 

XML界面(两个输入框,一个按钮):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="com.example.newsmanager.MainActivity" >
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/title" />
    <EditText 
       android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/title"/>
    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/timelength" />
    <EditText 
       android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:numeric="integer"
        android:id="@+id/timelength"/>"
   
    <Button 
       android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:onClick="save"
        android:text="@string/button"
        />
</LinearLayout>

 

之后我要在Activity里将界面的编辑框里面的值传到WEB

 

Activity(这里的线程问题在前面讲过):

package com.example.newsmanager;
 
import com.example.service.NewsService;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends Activity {
    private EditText titletext;
    private EditText lengthtext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
titletext=(EditText) findViewById(R.id.title);
lengthtext=(EditText) findViewById(R.id.timelength);
}
boolean flag;
    public void save(View view) throws Exception{
    	//开启线程
    	new Thread(new Runnable() {
        	String title=titletext.getText().toString();
        	String length=lengthtext.getText().toString();
@Override
public void run() {
boolean result;
try {
result = NewsService.save(title,length);
if(result){
//返回主线程显示
       runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
}
});
    
    	}else{
    	 runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
}
});
    	}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
    }
}


上面代码中的NewsService类以及save方法(这个类是用来处理信息,然后以get方式传往WEB端)。这里我要说一句,我们采用的GET方法,是将需要传递给WEB端的数据放在URL路径,然后WEB端进行解析得到的,所以我们要在方法中将URL路径给拼凑完成然后传给WEB(里面的IP是我tomcat服务器本机的ip)

package com.example.service;
 
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
 
public class NewsService {
    /*
     * 保存数据
     * title 标题
     * length 时长
     * */
public static boolean save(String title, String length) throws Exception{
String path="http://10.20.124.72:8080/videonews/ManagerServlet";
Map<String,String> map=new HashMap<String,String>();
map.put("title", title);
map.put("timelength", length);
return sendGETRequest(path,map,"UTF-8");
}
    /*
     * 发送Get请求
     * path请求路径
     * map请求参数
     * */
private static boolean sendGETRequest(String path, Map<String, String> map,String ecoding) throws Exception{
/*将路径拼成http://10.20.124.72:8080/videonews/ManagerServlet?title=XXX&timelength=90*/
StringBuilder url=new StringBuilder(path);
url.append("?");
//map迭代器Entry<Key, Value>
for(Map.Entry<String, String> entry:map.entrySet()){
url.append(entry.getKey()).append("=");
            //ecoding是上面传来的“UTF-8”,为了防止中文乱码
url.append(URLEncoder.encode(entry.getValue(), ecoding));
url.append("&");
}
url.deleteCharAt(url.length()-1);
URL url2=new URL(url.toString());
HttpURLConnection conn=(HttpURLConnection) url2.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
 
}

上面如果传到WEB端是成功的(即conn.getResponseCode() = 200),那么安卓端就会显示“登陆成功”,而且在WEB编辑器的控制台会以System.out.println方式打印出你传去的信息。

 

效果:

 

这里仅仅是一个传值的演示,没用用到数据库和输入输出流,真正做开发的时候这些东西是少不了的,所以要学会将东西结合起来应用。

相关文章
|
25天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
12 0
|
2天前
|
Linux 编译器 Android开发
FFmpeg开发笔记(九)Linux交叉编译Android的x265库
在Linux环境下,本文指导如何交叉编译x265的so库以适应Android。首先,需安装cmake和下载android-ndk-r21e。接着,下载x265源码,修改crosscompile.cmake的编译器设置。配置x265源码,使用指定的NDK路径,并在配置界面修改相关选项。随后,修改编译规则,编译并安装x265,调整pc描述文件并更新PKG_CONFIG_PATH。最后,修改FFmpeg配置脚本启用x265支持,编译安装FFmpeg,将生成的so文件导入Android工程,调整gradle配置以确保顺利运行。
20 1
FFmpeg开发笔记(九)Linux交叉编译Android的x265库
|
7天前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android&#39;s AsyncTask simplifies asynchronous tasks for brief background work, bridging UI and worker threads. It involves execute() for starting tasks, doInBackground() for background execution, publishProgress() for progress updates, and onPostExecute() for returning results to the main thread.
9 0
|
7天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
8 0
|
16天前
|
XML 开发工具 Android开发
构建高效的安卓应用:使用Jetpack Compose优化UI开发
【4月更文挑战第7天】 随着Android开发不断进化,开发者面临着提高应用性能与简化UI构建流程的双重挑战。本文将探讨如何使用Jetpack Compose这一现代UI工具包来优化安卓应用的开发流程,并提升用户界面的流畅性与一致性。通过介绍Jetpack Compose的核心概念、与传统方法的区别以及实际集成步骤,我们旨在提供一种高效且可靠的解决方案,以帮助开发者构建响应迅速且用户体验优良的安卓应用。
|
18天前
|
监控 算法 Android开发
安卓应用开发:打造高效启动流程
【4月更文挑战第5天】 在移动应用的世界中,用户的第一印象至关重要。特别是对于安卓应用而言,启动时间是用户体验的关键指标之一。本文将深入探讨如何优化安卓应用的启动流程,从而减少启动时间,提升用户满意度。我们将从分析应用启动流程的各个阶段入手,提出一系列实用的技术策略,包括代码层面的优化、资源加载的管理以及异步初始化等,帮助开发者构建快速响应的安卓应用。
|
18天前
|
Java Android开发
Android开发之使用OpenGL实现翻书动画
本文讲述了如何使用OpenGL实现更平滑、逼真的电子书翻页动画,以解决传统贝塞尔曲线方法存在的卡顿和阴影问题。作者分享了一个改造后的外国代码示例,提供了从前往后和从后往前的翻页效果动图。文章附带了`GlTurnActivity`的Java代码片段,展示如何加载和显示书籍图片。完整工程代码可在作者的GitHub找到:https://github.com/aqi00/note/tree/master/ExmOpenGL。
19 1
Android开发之使用OpenGL实现翻书动画
|
18天前
|
Android开发 开发者
Android开发之OpenGL的画笔工具GL10
这篇文章简述了OpenGL通过GL10进行三维图形绘制,强调颜色取值范围为0.0到1.0,背景和画笔颜色设置方法;介绍了三维坐标系及与之相关的旋转、平移和缩放操作;最后探讨了坐标矩阵变换,包括设置绘图区域、调整镜头参数和改变观测方位。示例代码展示了如何使用这些方法创建简单的三维立方体。
15 1
Android开发之OpenGL的画笔工具GL10
|
20天前
|
SQL 前端开发 Java
五邑大学餐厅网络点餐系统设计与实现(包含完整源码详细开发过程)
五邑大学餐厅网络点餐系统设计与实现(包含完整源码详细开发过程)
|
21天前
|
Android开发
Android调用相机与相册的方法2
Android调用相机与相册的方法
17 0