引用第三方进行Android前端与web后台的数据交互

1.首先你需要导入jar包,如图:

2.然后把jar包放入Project(Android)

3.注意:useLibrary 'org.apache.http.legacy'这句话需要放入Project你所在的项目里的gradle,版本处。看图:

引用第三方进行Android前端与web后台的数据交互_第1张图片

4.web后台服务做一个简易的登录页面

演示代码:

引用第三方进行Android前端与web后台的数据交互_第2张图片


loginServlet

package com.ZGL.servlet;

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 LoginServlet extends HttpServlet{
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			//获取用户名和密码
			String uname=req.getParameter("uname");
			String upass=req.getParameter("upass");
			System.out.println(uname+" "+upass);
			String result=null;
			//判断
			if("admin".equals(uname)&&"123".equals(upass)){
				result="success";
			}else{
				result="fail";
			}
			PrintWriter pw=resp.getWriter();
			pw.write(result);
			pw.close();
		}
		
		@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			doPost(req, resp);
		}
		
	
}

还需要xml配置


5.Android前端代码演示:

布局:


Activity:

public class MainActivity extends AppCompatActivity {

    private EditText et_main_uname;
    private EditText et_main_upass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_main_uname = (EditText) findViewById(R.id.et_main_uname);
        et_main_upass = (EditText) findViewById(R.id.et_main_upass);
    }
    public  void  loginAsyncHttpClient(View v){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();
        String path="http://192.168.43.238:8080/Myweb_01/login.do";
        AsyncHttpClient ahc=new AsyncHttpClient();
        RequestParams p=new RequestParams();
        p.put("uname",uname);
        p.put("upass",upass);
        ahc.post(this,path,p,new TextHttpResponseHandler(){
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
                super.onFailure(statusCode, headers, responseBody, error);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                super.onSuccess(statusCode, headers, responseBody);
                Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_SHORT).show();
            }
        });
    }


xml:网络权限配置:
<uses-permission android:name="android.permission.INTERNET">uses-permission>





你可能感兴趣的:(Android)