Android as the client and PC as the server: Network Communication

Source: Internet
Author: User

This project implements network communication. The Android mobile client sends a request to the PC server to display Mysql Data on the PC on the mobile phone.

The PC server uses javaweb to write a servlet. The Android mobile client requests this servlet, And the servlet queries the data and returns it to the mobile client. The server is tomcat.

To make it clearer, we now create a test table in MySQL.

 

create table test(name varchar(20) primary key);

Insert several records. We can insert Chinese characters here. We can solve this problem in case of garbled characters.

Insert into test values ('zhang san'); insert into test values ('Li si'); insert into test values ('wang wu ');

 

Inserted successfully

 

Let's talk less about the Code:

 

 

PC Server

I created a javaweb project using myeclipse, which consists of a Data Query Class dbmanager. Java and a servlet (loadmessage. Java ).

 

Dbmanager. Java

Package COM. njue. dbmanager; import Java. AWT. list; import Java. SQL. *; import Java. util. arraylist; import Org. OMG. CORBA. object; public class dbmanager {; string username = "root"; string Password = "123456"; connection conn = NULL; statement stmt = NULL; string url = "JDBC: mysql: // localhost: 3306/MySQL "; arraylist <string> List = new arraylist <string> (); string SQL; Public dbmanager () {SQL =" select * from test; "; try {class. forname ("com. mySQL. JDBC. driver "); Conn = drivermanager. getconnection (URL, username, password); stmt = Conn. createstatement (); resultset rst1_stmt.exe cutequery (SQL); While (RST. next () {// string name = new string (RST. getstring ("name "). getbytes ("Latin1"), "UTF-8"); string name = new string (RST. getstring ("name "). getbytes ("Latin1"), "gb2312"); // whether this sentence is required or not, subject to your no garbled characters. // no conversion is required, directly write it as string name = rst. getstring ("name"); list. add (name);} rst. close ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public arraylist <string> getlist () {return list ;}}

 

Loadmessage. Java
package com.amaker.servlet;import java.awt.List;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.njue.DBManager.DBManager;public class loadMessage extends HttpServlet {public loadMessage() {super();}public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here} public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//request.setCharacterEncoding("UTF-8");response.setContentType("text/html; charset=UTF-8" );PrintWriter out = response.getWriter();     String message="";     DBManager db=new DBManager();       ArrayList<String> list=db.getList();       for(int i=0;i<list.size();i++){       message=message+list.get(i)+"\r\n";       }out.print(message);out.flush();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request,response);}public void init() throws ServletException {// Put your code here}}

 

 

Android mobile client code:

Androidclientactivity. Java

Package COM. njue. androidclient; import android. app. activity; import android. OS. bundle; import android. widget. textview; public class androidclientactivity extends activity {/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); textview TV = (textview) findviewbyid (R. id. TV); // query the returned result string result = httputil. querystringforpost ("http: // 10.0.2.2: 8080/androidweb/servlet/loadmessage"); // string result = httputil. querystringforpost ("http: // 122.88.34.123: 8080/androidweb/servlet/loadmessage"); TV. settext (result );}}

 

Httputil. Java

Package COM. njue. androidclient; import Java. io. ioexception; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. client. clientprotocolexception; 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. util. entityutils; public class httputil {// basic URL // obtain the GET request object requestpublic static htT Pget gethttpget (string URL) {httpget request = new httpget (URL); return request;} // get the post request object requestpublic static httppost gethttppost (string URL) {httppost request = new httppost (URL); return request;} // obtain the response object responsepublic static httpresponse gethttpresponse (httpget request) throws clientprotocolexception according to the request, ioexception {httpresponse response = new defaulthttpclient(cmd.exe cute (request); return r Esponse;} // obtain the response object responsepublic static httpresponse gethttpresponse (httppost request) throws clientprotocolexception, ioexception {httpresponse response = new response cute (request); return response ;} // send a POST request to obtain the response query result public static string querystringforpost (string URL) {// obtain the httppost object httppost request = httputil Based on the URL. gethttppost (URL); string result = NULL; try {// get the response object httprespons E response = httputil. gethttpresponse (request); // determines whether the request is successful if (response. getstatusline (). getstatuscode () = 200) {// get the response result = entityutils. tostring (response. getentity (); // result = new string (result. getbytes ("8859_1"), "gb2312"); this sentence is optional. Return result if you do not see any garbled code;} catch (clientprotocolexception e) {e. printstacktrace (); Result = "network exception! "; Return result;} catch (ioexception e) {e. printstacktrace (); Result =" network exception! "; Return result;} return NULL ;}}

 

Of course, you must add the network access permission to androidmanifest. xml:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

 

Note that when writing the server host number, do not write localhost or 127.0.0.1, because although the android simulator and the server program are on the same computer, the two are independent systems after all, we can use 10.0.2.2 to access the local machine.

 

Running result:

 

This is running on the simulator. Some people have the idea that they should change the IP address to the real IP address of their computer and take the client to the real machine for an experiment, however, a "network exception" is displayed and cannot be accessed. This involves network issues, which are actually very simple. The next blog will explain in detail to solve this problem.

 

 

Supplement: You can upload two projects to access MySQL or the access database.

:Http://download.csdn.net/detail/pzhtpf/4388157

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.