四、Android端代码
在AndroidManifest.xml加入:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
- package org.xiazdong.network.submit;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- private EditText name, age;
- private Button getbutton, postbutton;
- private OnClickListener listener = new OnClickListener() {
- @Override
- public void onClick(View v) {
- try{
- if (getbutton == v) {
- /*
- * 因为是GET请求,所以需要将请求参数添加到URL后,并且还需要进行URL编码
- * URL = http://192.168.0.103:8080/Server/PrintServlet?name=%E6%88%91&age=20
- * 此处需要进行URL编码因为浏览器提交时自动进行URL编码
- * */
- StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/PrintServlet");
- buf.append("?");
- buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");
- buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));
- URL url = new URL(buf.toString());
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("GET");
- if(conn.getResponseCode()==200){
- Toast.makeText(MainActivity.this, "GET提交成功", Toast.LENGTH_SHORT).show();
- }
- else Toast.makeText(MainActivity.this, "GET提交失败", Toast.LENGTH_SHORT).show();
- }
- if (postbutton == v) {
- /*
- * 如果是POST请求,则请求参数放在请求体中,
- * name=%E6%88%91&age=12
- *
- * */
- StringBuilder buf = new StringBuilder();
- buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");
- buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));
- byte[]data = buf.toString().getBytes("UTF-8");
- URL url = new URL("http://192.168.0.103:8080/Server/PrintServlet");
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true); //如果要输出,则必须加上此句
- OutputStream out = conn.getOutputStream();
- out.write(data);
- if(conn.getResponseCode()==200){
- Toast.makeText(MainActivity.this, "GET提交成功", Toast.LENGTH_SHORT).show();
- }
- else Toast.makeText(MainActivity.this, "GET提交失败", Toast.LENGTH_SHORT).show();
- }
- }
- catch(Exception e){
- }
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- name = (EditText) this.findViewById(R.id.name);
- age = (EditText) this.findViewById(R.id.age);
- getbutton = (Button) this.findViewById(R.id.getbutton);
- postbutton = (Button) this.findViewById(R.id.postbutton);
- getbutton.setOnClickListener(listener);
- postbutton.setOnClickListener(listener);
- }
- }

