Android communicates with Sea server

Source: Internet
Author: User
Tags php server php json

Today, a small project to communicate with each other on Android and sea is not very difficult, and only a few lines of code can be implemented.

The first step:

On the Android home page, be sure to Super.oncreate (savedinstancestate) inside the OnCreate function, plus the following two sentences

Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). build ());
Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). build ());

, the corresponding header file is import Android.os.StrictMode; (Does not use what packages are imported).

The following buttons are invoked to connect to the server and get the data:

(Remember to set permissions <uses-permission android:name= "Android.permission.INTERNET"/> and <uses-sdk android:minsdkversion= " 8 "/>)

Button = (button) Findviewbyid (R.id.button);
Button.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
String url = "url (server address)";
String name = "220202051011";
String pwd = "123456";
String flag = XIN.SAVE_PW (URL, name, PWD); (Call the function of the following class)
if (!flag.equals ("no")) {
Toast.maketext (linkactivity.this, Flag, Toast.length_long). Show ();
}else{
Toast.maketext (linkactivity.this, Flag, Toast.length_long). Show ();
}
}

});

Step Two:

Set up the data and transfer the data via ArrayList (post mode),

Public arraylist<namevaluepair> init (string Name, String pw) {//This function is used to initialize the list of arrays ArrayList
arraylist<namevaluepair> name = new Arraylist<namevaluepair> ();//define a key-value pair to row the array container
if (name!=null) {
Name.add (New Basicnamevaluepair ("name", name));//This sets the order that the PHP file receives, such as $_request["order", which is written according to your PHP own definition
}
if (pw!=null) {
Name.add (New Basicnamevaluepair ("PW", PW));//above I have defined a MySQL command, here is the database name, two parameters passed in, added flexibility
}

Return name;//back to set up the container
}

public string SAVE_PW (string url,string name, string pw) {
String k = "No";
InputStream Getcontentfromdb = null;//defines a variable that holds the input stream
try {
HttpClient http = new Defaulthttpclient ();//Turn on HTTP service
HttpPost post = new HttpPost (URL);//incoming URL, initialize the URL to post data
Post.setentity (New urlencodedformentity (init (name, PW)));//Send data here, see the init () function call No
HttpResponse response = Http.execute (post);//This is a real access, with the data set above
Httpentity Responsefromdb = response.getentity ();//Accept returned entities
Getcontentfromdb = Responsefromdb.getcontent ();//Accept entity content and save to input stream object

LOG.I ("Aaaaaaa", "STATA");
if (getcontentfromdb!=null) {
try {
BufferedReader reader = new BufferedReader (new InputStreamReader (Getcontentfromdb, "UTF-8"), 8);
The above function is to encode the contents of the input stream, the second best set UTF-8, and your MySQL table, if used iso-8859-1 may throw garbled error
StringBuilder info = new StringBuilder ();//define character container
String line = null;//is used to save each row of extracted data
while (line = Reader.readline ()) = null) {//guaranteed to read every row of data is not NULL
Info.append (line + "\ n");//Add each row
}
Getcontentfromdb.close ();//Close
result = Info.tostring ();//Data conversion
SYSTEM.OUT.PRINTLN (result);
} catch (Exception e) {
LOG.I ("Second Exception", e.tostring ());
}
try {
K = "";

Put the data php JSON data back here, remember, you PHP final output must be JSON data, otherwise, this will throw an exception
Jsonarray Jarray = new Jsonarray (result);
if (jarray.length () > 0) {//whether there is data
RowNum = Jarray.length ();//Gets the number of rows and saves
K = rownum+ "";
for (int i = 0; i < jarray.length (); i++) {
Jsonobject Json_data = Jarray.getjsonobject (i);//Line to get the JSON data that is received back
K + = json_data.getstring ("id") + "";
K + = json_data.getstring ("username") + "";
LOG.I ("Xxxxxxxxxxxx", K);
}
}
} catch (Exception e) {
LOG.I ("Three exception", e.tostring ());
}
K = "Yes";
return k;
}
} catch (Exception e) {
LOG.I ("tag", e.tostring ());
}
return k;
}

Step Three:

Code on the PHP server:

<?php

$conn =mysql_connect (sae_mysql_host_m. ': ').  Sae_mysql_port,sae_mysql_user,sae_mysql_pass); Configuration database
if (! $conn)
{
Die ("Connect Server Failed:". Mysql_error ());
}
if (!mysql_select_db (sae_mysql_db, $conn))
{
Die ("Select Database Failed:". Mysql_error ());
}

$Information =$_request["name"]; Obtained through $_request
$Information 2=$_request["PW"];

}

Inserting incoming data into the database

$sql = "INSERT into WeChat (Username,password) VALUES (' $Information ', ' $Information 2 ')";
$flag = mysql_query ($sql, $conn);


if ($flag) {
$sql 1 = "SELECT * from WeChat;";
$a = array ();
$list = mysql_query ($sql 1, $conn);
while ($s = MYSQL_FETCH_ASSOC ($list))
{
$a [] = $s;
}

Returns the array data to Android, the returned data is in JSON format: [{"": "}]
Print (Json_encode ($a));
}
Mysql_close ($conn);
?>

Android communicates with Sea server

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.