android通过HttpURLConnection/HttpClient(post)方式与servlet(tomcat)进行交互(servlet实现的功能是计算两个数字的积)

我的电脑里已经配置好了Tomcat.

Tomcat的安装和环境配置这里不再做演示。

今天我们做的实验内容是:


这里先写一个通过以HttpURLConnection的post方式进行通信,直接贴代码,代码里的注解写得很详细,对了我用的android studio和eclipse

eclipse端的代码往下看截图1-2,很简单,这里不再过多赘述

这里先交代一下HttpURLConnection实现流程:

1、创建HttpURLConnection实例

2、用openConnection创建HttpURLConnection实例

3、建立连接,可以通过connect()方法,也可以直接通过getOutputStream()方法建立连接

4、通过HttpURLConnection写数据与发送数据

5、通过getInputStream()方法,将HTTP请求发送到服务器,并取得返回数据

6、在AndroidManifest.xml文件中添加权限

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

android studio 端代码:

public class MainActivity extends AppCompatActivity {
    TextView t1;
    private Handler handler=new Handler(){
        //这里接受sendMessage()发来的数据msg1
        public void handleMessage(android.os.Message msg){
            Bundle bundle = new Bundle();
            bundle = msg.getData();
            String p = bundle.getString("result");
            if(p != null){
                t1.setText(p);
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText e1=(EditText) findViewById(R.id.editText1);
        final EditText e2=(EditText) findViewById(R.id.editText2);
        Button b1=(Button) findViewById(R.id.button);
        Button b2=(Button) findViewById(R.id.button2);
        t1=(TextView) findViewById(R.id.textView);
        //设置按钮“计算结果”的点击事件
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //定义路径LOGIN_URL,模拟器进行测试时10.0.2.2表示本机的IP地址,8080代表端口号,androidexphttpclient是我在eclipse里创建的模拟服务器的包名
                // calculateservlet是servlet的类名,见下面的图1-1和1-2
                final String URL = "http://10.0.2.2:8080/androidexphttpclient/calculateservlet";
                if (e1.getText().toString().isEmpty()||e2.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
                }
                else{
                    //开启访问服务器的线程,android4.0之后不能在UI线程访问网络,子线程也不能更新UI界面
                    new 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值