我的电脑里已经配置好了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