Android 简单后端服务器的搭建方法
一、后端服务器搭建,需要用到 jsp+java+tomcat。
1、安装myeclipse,不细说,自己下载安装,里面包含服务器apache-tomcat。
2、testServlet.java代码
package com.liuxiang;
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 testServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("server " + "doget\n");
process(request, response);
//doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//process(request, response);
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
String name=request.getParameter("user");
String pwd=request.getParameter("password");
String message = ":Welcome to android!";
System.out.println("server " + "dopost\n");
if (name.equals("admin")&&pwd.equals("android"))
response.getWriter().write(name+message);
else
response.getWriter().write("Input Error!");
}
private void process(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String username = request.getParameter("user");
String password = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Welcome!</title></head>");
out.println("<body> Welcome my dear friend!<br>");
out.println("Your name is: " + username + "<br>");
out.println("And your age is: " + password + "</body></html>");
out.flush();
out.close();
}
}
二、android app 端
1、MainActivity.java
package com.example.httpandroidappdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
EditText e1, e2;
Button b_get, b_post;
//申请读写权限
String permissions[] = {Manifest.permission.INTERNET};
private WebView webView;
private String TAG="http android app server demo:";
/**
* 根据输入流返回一个字符串
* @param is
* @throwsException
*/
//接受数据的函数
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 mes=baos.toString();
baos.close();
return mes;
}
public void LoginByDopost(String username,String password) {
String path = "http://192.168.2.84:8080/aboutAndroid/servlet/testServlet";
System.out.println("demon logindogo"+"username="+username+" password="+password);
try {
URL url = new URL(path);
//打开一个url连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置conn 的参数
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
//获取服务器返回的状态码
//post和get方式登录的区别 (2)**************要设置头信息 Content-Type Content-Length
String data = "user=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8") + "";
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.getBytes().length + "");
//post和get方式登录的区别 (3)************** 以流的形式把数据写给服务器
conn.setDoOutput(true); //设置一个标记 允许输出
conn.getOutputStream().write(data.getBytes());
int code = conn.getResponseCode();
System.out.println(TAG+"code="+code);
if(code==200){
//接受数据
InputStream is=conn.getInputStream();
String state=getStringFromInputStream(is);
System.out.println(TAG+"state="+state);
}
}catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String LoginByGet(String username,String password){
HttpURLConnection conn=null;
//一下为自己的服务器ip,10.0.2.2:8081是本机的ip,android中本机ip不是localhost
String myurl = "http://192.168.2.84:8080/aboutAndroid/servlet/testServlet?";
Log.v(TAG, "LoginByGet: ");
try {
//拼接字符串向服务器传值
String data="user="+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();
System.out.println(TAG+"code="+code);
if(code==200){
//接受数据
InputStream is=conn.getInputStream();
String state=getStringFromInputStream(is);
System.out.println(TAG+"state="+state);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(TAG+e);
}finally{
if(conn!=null){
conn.disconnect();
}
}
return null;
}
public void LoginHttpGet()
{
String url = "http://192.168.2.84:8080/aboutAndroid/servlet/testServlet";
Log.v(TAG, "LoginHttpGet: ");
url = url + "?user=" + e1.getText().toString() + "&password=" + e2.getText().toString();
HttpClient client = new DefaultHttpClient();
try {
HttpGet httpGet = new HttpGet(new URI(url));
HttpResponse httpResponse = client.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String out = EntityUtils.toString(httpEntity);
new AlertDialog.Builder(MainActivity.this).setMessage(out).create().show();
Log.v(TAG, "receive data: " + out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void LoginHttpDopost()
{
String url = "http://192.168.2.84:8080/aboutAndroid/servlet/testServlet";
Log.v(TAG, "LoginHttpDopost: ");
String name = e1.getText().toString();
String pwd = e2.getText().toString();
NameValuePair nameValuePair1 = new BasicNameValuePair("user", name);
NameValuePair nameValuePair2 = new BasicNameValuePair("password", pwd);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
try
{
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(requestHttpEntity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String out = EntityUtils.toString(httpEntity);
new AlertDialog.Builder(MainActivity.this).setMessage(out).create().show();
Log.v(TAG, "LoginHttpDopost: "+ out);
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText1);
e2 = (EditText) findViewById(R.id.editText2);
b_get = (Button) findViewById(R.id.buttonget);
//ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.INTERNET},1);
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
webView = (WebView) findViewById(R.id.wv);
//如果只写下面这一句,会提示无法访问
//加载网页需要连接互联网的权限,需要在AndroidManifest中进行声明
//这样的好处:可以让用户很清楚的看到app所需要的权限
//用户并不清楚和重视权限问题,造成了病毒问题的泛滥。其实是可以避免的!
webView.loadUrl("http://192.168.2.84:8080/aboutAndroid/");
b_get.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
LoginByGet("admin","android");
LoginHttpGet();
}
});
b_post = (Button) findViewById(R.id.buttonpost);
b_post.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
LoginByDopost("admin","android");
LoginHttpDopost();
}
});
}
}
2、布局文件 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="输入进入服务器的用户名和密码:" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="admin"/>
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="android"/>
<Button
android:id="@+id/buttonget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get进入" />
<Button
android:id="@+id/buttonpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post进入" />
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wv"></WebView>
</LinearLayout>
三、测试,在真机上测试ok,这里为了方便演示,在模拟器上测试。
四、源码下载路径:https://download.csdn.net/download/qq_37858386/13012979