Blogs are dedicated to Android and Java web as soon as they are blogged. Hope to help me as a beginner's companion, but also please prawn advice.
For example, I believe that most of the comrades who have studied Java will choose between these two paths. However, they complement each other, regardless of you or me.
The Java web that the author learns first, the simplest use Tomcat, the local area network that builds through route, can be accessed through mobile browser, realize simple.
Inter-LAN access. Having studied Android for half a month unexpectedly, I want to complete it through App. At the same time, the lab also has hardware partners, together.
A little thing that can measure temperature and humidity in real time through Bluetooth module is tampered with. If the measured data are connected to the background, we can start to do small-scale data analysis.
Now.
Let's get down to the main topic:
Web side: Interlij Idea 2016.3.3
Server: apache-tomcat-7.0.42
Android: Android Studio 2.1.1
First create the server side:
The code is as follows:
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter;
public class loginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{ String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username+":"+password); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String msg = null; if(username != null && username.equals("xiaoming") && password != null && password.equals("123")){ Msg= "successful login"; } else { MSG = login failure; } out.print(msg); out.flush(); out.close(); } }
Override the doGet() method. When the user name is "xiaoming" and the password is "123", return "Log in Successfully" or "Log back" fails.“
Mobile terminal
Inventory file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.exam">
<application android:allowBackup="true" android:icon="@drawable/logo" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".loginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Must give the network authority!! Network permission!! Network! Net!
layout code: <? XML version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Name" android:ems="10" android:id="@+id/username" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/psw" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submission" android:id="@+id/btn" android:layout_gravity="right" />
</LinearLayout>
The simplest layout, not to mention much.
Activity code: import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView;
import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;
public class loginActivity extends Activity{
Button btn; TextView uname; TextView psw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); psw= (TextView) findViewById(R.id.psw); uname= (TextView) findViewById(R.id.username); btn= (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(v.getId()==R.id.btn){ String username=uname.getText().toString(); String pass= psw.getText().toString(); String urlStr="http://192.168.6.2/loginServlet?"+ "username="+username+"&password="+pass; Log.d("lll","......."+urlStr); new Async().execute(urlStr); } } }); } class Async extends AsyncTask<String, Object,String> { @Override //Background Subthread protected String doInBackground(String... params) { String result=""; String path=params[0]; try { URL url=new URL(path); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); //Reading and Writing of Documents InputStream is=conn.getInputStream(); byte[] b=new byte[2048]; int len =0; while ((len=is.read(b))!=-1) { Log.d("lll", len+""); result=new String (b); Log.d("lll","........"+result); Thread.sleep(200);//Process dormancy, easy to see the effect } } catch (Exception e) { e.printStackTrace(); } return result; } //Host thread for real-time update protected void onProgressUpdate(Object... values) { super.onProgressUpdate(values); } //Front-end main thread protected void onPostExecute(String result) { showDialog(result); super.onPostExecute(result); } } private void showDialog(String msg){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(msg).setCancelable(false).setPositiveButton("Determine", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); }
}
This is the key to the problem. The first step is to add login to the button click event directly to connect to the Internet. But this will report android.os.NetworkOnMainThreadException. The reason is that after Android 4.0, Internet connection operations must be placed in subprocesses. So we have to resort to some objects. The author uses the class AsyncTask.
AsyncTask is an abstract class. When we use it, we need to define a derived class of AsyncTask and rewrite related methods. The declaration of the AsyncTask class is as follows:
public abstract class AsyncTask<Params, Progress, Result>
As we can see, AsyncTask is a generic class. Its three type parameters have the following meanings:
Params: parameter type of doInBackground method; Progress: The progress type of background tasks performed by AsyncTask; Result: The return result type of the background task. Let's take a look at the main methods that the AsyncTask class provides for us:
onPreExecute()// This method is called before the background task is executed for some preparation. doInBackground(Params... params) // This method defines the background task to be performed, in which publishProgress can be invoked to update the progress of the task (onProgressUpdate method is invoked internally in publishProgress) onProgressUpdate(Progress... values) // Called internally by publishProgress to indicate task progress updates After the onPostExecute(Result result) // background task is executed, this method is called, and the parameter is the return result of the background task. onCancelled()// This method is called when the background task is cancelled
Among the above methods, except that the doInBackground method is executed by the internal thread pool of AsyncTask, the other methods are executed in the main thread.
Next, just change the address and port of the URL to the IP and Tomcat ports of the PC in the LAN.
If it is still inaccessible, it is recommended to close the PC firewall and test it.