美文网首页工作生活
Android-async-http 之服务器接收请求以及and

Android-async-http 之服务器接收请求以及and

作者: Xeon_CC | 来源:发表于2019-06-30 21:04 被阅读0次

为什么要写这篇博客呢?因为我觉得使用这种http请求框架 进行客户端与服务器的通信十分简单,而且它很有用。举个例子,客户端访问服务器的数据库的时候,那些SQL语句相关的代码不应该写在android客户端,而是SQL代码放在后台,客户端只负责发送请求参数给服务器,然后服务器将接收到的请求参数之后,再对数据库进行操作。

1

准备3个jar包httpcore-4.4.3.jar,android-async-http-1.4.8.jar,httpclient-4.3.6.jar
链接:https://pan.baidu.com/s/1CK1NPfHBtppF-lxR-RcUmQ
密码:f16a

2

android客户端代码:
MainActivity

package com.example.xeonrnc.req_resp;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;
 
public class MainActivity extends AppCompatActivity {
    //这是服务端名为req_resp的servlet的url
    //这个servlet发布到tomcat运行的
    String url="http://192.168.43.173:8080/request_parameter/servlet/req_resp";
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn=(Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                send_request();
            }
        });
 
    }
 
    public void send_request(){
        AsyncHttpClient client=new AsyncHttpClient();
        RequestParams params=new RequestParams();
        //向设置请求参数
        params.put("username","张三");
        params.put("password","123456");
        params.put("age","666");
        client.post(this, url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //在servlet里面调用response.getWriter()方法,写入的字符串都会传到下面的response的变量里面去
                //通过new String(bytes)可以获取服务器响应的内容
                String response=new String(bytes);
                //根据逗号的分隔,将服务器返回的每一条信息存到数组里面
                String result[]=response.split(",");
                System.out.println("下面是服务器响应返回的数据:");
                for(int j=0;j<result.length;j++){
                    System.out.println(result[j]);
                }
 
            }
 
            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
 
            }
        });
    }
 
 
}

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/btn"
            android:text="向服务器发送请求"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
 
</android.support.constraint.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xeonrnc.req_resp">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 
    <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:usesCleartextTraffic="true">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="org.apache.http.legacy" android:required="false" />
    </application>
 
</manifest>

3

新建web项目,这里java EE版本为:


image.png

项目名为:request_parameter
servlet 类名为 req_resp
服务端 servlet 代码

package request_parameter;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/req_resp")
public class req_resp extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    public req_resp() {
        super();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        System.out.println("下面是客户端请求的内容:");
        System.out.println("用户名是:"+request.getParameter("username"));
        System.out.println("密码是:"+request.getParameter("password"));
        System.out.println("年龄是:"+request.getParameter("age"));
        //服务器响应信息给android客户端,当然响应的内容是可以自定义的,这里用逗号隔开是为了在android客户端可以根据逗号来切割字符串,区分每个请求对应的响应
        response.getWriter().println(request.getParameter("username")+","+request.getParameter("password")+","+request.getParameter("age"));
        doGet(request, response);
    }
 
}

web.xml 文件
设置servlet映射

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>request_parameter</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>req_resp</servlet-name>
    <servlet-class>request_parameter.req_resp</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>req_resp</servlet-name>
    <url-pattern>/servlet/req_resp</url-pattern>
  </servlet-mapping>
</web-app>

4

运行效果展示:
在android客户端点击”向服务器发送请求“的按钮以后:
这是服务端控制台打印的信息:


image.png

这是android客户端控制台的打印的信息:


image.png

相关文章

网友评论

    本文标题:Android-async-http 之服务器接收请求以及and

    本文链接:https://www.haomeiwen.com/subject/emqicctx.html