Android端通过HttpURLConnection连接web服务器,通过post方法发送json数据,后台拿到json数据并解析
- Android端
(1)布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="@+id/account"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="账户" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="密码" />
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="姓名" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false" />
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="登录" />
</LinearLayout>
(2)MainActivity.java
package com.example.logindemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText account;
EditText password;
EditText name;
public TextView textView;
Button login;
org.json.JSONObject userInfo = new JSONObject();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
account=(EditText)findViewById(R.id.account);//输入账户
password=(EditText)findViewById(R.id.password);//输入密码
name=(EditText)findViewById(R.id.name);//输入密码
textView=(TextView)findViewById(R.id.text);
login=(Button)findViewById(R.id.login);
/**
* 登录逻辑
* 将输入的账号和密码获取
* 判断是否为空
*
*/
// final User user=new User();
// user.setUserName("张三");
// user.setUserPassword(password.getText().toString());
// user.setUserPhone("1836666666");
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
User user=new User();
user.setUserPhone(account.getText().toString());
user.setUserPassword(password.getText().toString());
user.setUserName(name.getText().toString());
if (!(account.getText().toString().isEmpty())
&& !(password.getText().toString().isEmpty())) {
loginPost(user);
} else {
Toast.makeText(MainActivity.this, "账号、密码都不能为空!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void loginPost(User user){
String name=user.getUserName();
String password=user.getUserPassword();
String phone=user.getUserPhone();
/**
* 192.168.0.100为电脑ipv4地址
* Demo_Database为eclipse中的工程名
* TestServlet为要提交到的servlet名
*/
String path="http://192.168.0.100:8080/Demo_Database/TestServlet";
new MyPostTask().execute(name,password,phone,path);//调方法
}
class MyPostTask extends AsyncTask<String,Integer,String>{
@Override
protected String doInBackground(String... params) {
String name=params[0];
String password=params[1];
String phone=params[2];
String path=params[3];
HttpURLConnection conn=null;
JSONObject userJSON = new JSONObject();
try {
userJSON.put("name",name);
userJSON.put("password",password);
userJSON.put("phone",phone);
String content = String.valueOf(userJSON);
try {
URL url=new URL(path);
conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(8000);//超时时间
/**
* conn.setRequestProperty("Content-Length",s.length()+"");
* 这条语句可能会导致报java.net.ProtocolException: exceeded content-length limit of 26 bytes 错误
*/
// conn.setRequestProperty("Content-Length",s.length()+"");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setDoOutput(true);//允许对外输出数据
conn.setDoInput(true);
OutputStream os=conn.getOutputStream();//写数据OutputStream
os.write(content.getBytes());//把数据传递给服务器了
os.flush();
os.close();
Log.d("code","code"+conn.getResponseCode());
System.out.println(conn.getResponseCode());
if(conn.getResponseCode()==200){//拿到返回结果
InputStream is=conn.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=br.readLine();
return str;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
Log.d("JSON",s);//打印服务器返回标签
//flag=true;
switch (s){
//判断返回的状态码,并把对应的说明显示在UI
case "100":
textView.setText(s+":登录失败,密码不匹配或账号未注册");
break;
case "200":
textView.setText(s+":登录成功");
break;
default:
textView.setText("异常");
}
Log.d("JSON","验证后");
}
}
}
(3)AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.logindemo">
<!--网络连接权限-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_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"
android:networkSecurityConfig="@xml/network_security_config"
>
<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>
(4)User.java
package com.example.logindemo;
public class User {
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
private String userPhone;//手机号码
private String userName;//昵称
private String userPassword;//密码
public User(){
}
}
- web服务器端
(1)eclipse中新建名为Demo_Database的web工程
(2)TestServlet
package Demo_Database;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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 com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
/**
* Servlet implementation class TestServlet
*/
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @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 {
int code = 200;
String streamIn = inputStreamToString(new BufferedInputStream(request.getInputStream()));
System.out.println(streamIn);
JSONObject object = JSONObject.fromObject(streamIn);
object.put("userJSON",streamIn );
JSONObject userInfo = JSONObject.fromObject(object.getString("userJSON"));
String name=userInfo.getString("name");
String password=userInfo.getString("password");
String phone=userInfo.getString("phone");
System.out.println(name+" "+password+" "+phone);
response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
//
// PrintWriter out = response.getWriter();
// out.write("成功");
// out.close();
PrintWriter out = response.getWriter();
String json=JSON.toJSONString(code);
out.println(json);
out.flush();
out.close();
}
public String inputStreamToString(InputStream inputStream) throws IOException {
int len = 0;
byte[] butter = new byte[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((len = inputStream.read(butter)) != -1) {
String s = new String(butter, 0, len, "UTF-8");
stringBuffer.append(s);
}
return stringBuffer.toString();
}
}
(3)jar包
commons-beanutils-1.9.2.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
fastjson-1.2.22.jar
json-lib-2.4-jdk15.jar