Android Studio创建网络连接工程试验
1 新建工程
File–》new–》project,然后一路next,最后finish即可。
2 Android Studio添加必要的代码和依赖
2.1 AndroidManifest文件
添加了两句网络访问权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hong.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2.2 添加网络访问工具GetPostUtil.java
package com.hong.myapplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* Created by FR on 2017/4/14.
*/
public class GetPostUtil {
/**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* @param params 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendGet(String url, String params)
{
String result = "";
BufferedReader in = null;
try
{
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
/*
* 建立实际的连接
* 如果需要发送POST请求,则需要获取URLConnection的OutputStream
* 然后再向网络中输出请求参数
*/
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet())
{
System.out.println(key + "--->" + map.get(key));
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL发送POST方法的请求
* @param url 发送请求的URL
* @param params 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendPost(String url, String params)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 向网络中输出请求参数
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
switch (result += "\n" + line) {
}
// Log.i("main",line );
}
}
catch (Exception e)
{
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}
2.3 修改主活动布局
仅仅增加了一个id便于后续在主活动java中控制
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/hellotxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
2.4 修改主活动MainActivity.java
package com.hong.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private String mResponse3 ;
private String massage; //用于接收服务器返回的信息
private static String PATH = "http://172.20.10.12:8080/Test_Servlet/Login_Servlet"; // 需要改成服务器地址
private TextView hellotxtt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hellotxtt= findViewById(R.id.hellotxt);
hellotxtt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//给服务器发一条信息:areyouok
//向服务器发一条命令,并获得修改成功的标志,确认后给用户弹出提示
new Thread() {
@Override
public void run() {
String mResponse = GetPostUtil.sendPost(PATH, "areyouok");
Log.i("main", mResponse);
String[] str = mResponse.split("@");
Log.i("main", "str[1]="+str[1]);
if(str[1].equals("yes")){
Log.i("main", "服务器说它ok");
}else{
Log.i("main", "服务器没有应答");
}
}
}.start();
}
});
}
}
3 服务器端代码
package com.dj.test;
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;
import org.codehaus.jackson.map.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import com.dj.entity.EnvData;
import com.dj.entity.User;
/**
* Servlet implementation class Login_Servlet
*/
@WebServlet("/Login_Servlet")
public class Login_Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PANDUAN = "areyouok";
/**
* @see HttpServlet#HttpServlet()
*/
public Login_Servlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String panduan = request.getParameter(PANDUAN);
if(panduan==null) {//如果panduan为空,直接退出
System.out.println("panduan为空");
return;
}
//如果不为空则继续下面的处理
//用json格式发送 执行下列代码前要先把两个相关jar包放在该放的位置
String yes = "@yes@";
ObjectMapper om1 = new ObjectMapper();
om1.writeValue(response.getOutputStream(),yes);
System.out.println("yes".toString());
}
}
4 测试结果
安卓端:
05-05 21:25:06.068 25571-25803/com.hong.myapplication I/main: "@yes@"
05-05 21:25:06.068 25571-25803/com.hong.myapplication I/main: str[1]=yes
05-05 21:25:06.068 25571-25803/com.hong.myapplication I/main: 服务器说它ok
服务器端:
五月 05, 2020 9:20:52 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 883 ms
yes