第十五天 乐在其中-Android与远端之POST方式

         4月26日,晴天。“已是早春二月天,今夜忽遇倒春寒”。

   1、服务器端

          (1)工程视图


         (2)ServletForPost.java
package com.servlet.post;

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("/ServletForPost")
public class ServletForPost extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ServletForPost() {
        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");
		String name= request.getParameter("name");
		String age= request.getParameter("age");
		System.out.println("name from POST method: " + name );
		System.out.println("age from POST method: " + age );
	}
}
               (4)运行http://192.168.23.1:8080/ServerForPOST/ServletForPost
          注意:IP:192.168.23.1:8080,是WIFI共享精灵设置的虚拟的无线网卡的IP,IP自然由虚拟的无线路由分配,使用手机连接,会自动给手机分配同一网段的IP:如:192.168.23.2
         因为在android模拟器中访问本机中的tomcat服务器时,注意:不能写localhost,因为模拟器是一个单独的手机系统,所以要写真是的IP地址。否则无法访问到服务器。
        2、手机端代码
          (1)工程视图

                (2)MainActivity.java

package com.androidpostmethod;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText titleText;
	private EditText lengthText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		titleText = (EditText) this.findViewById(R.id.title);
		lengthText = (EditText) this.findViewById(R.id.length);
	}

	public void save(View v) {
		String title = titleText.getText().toString();
		String length = lengthText.getText().toString();
		try {
			boolean result = false;
			result = UploadUserInformationByPostService.save(title, length);
			if (result) {
				Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(this, R.string.fail, Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "Exception error", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
              (3) UploadUserInformationByPostService.java

package com.androidpostmethod;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class UploadUserInformationByPostService {
	public static boolean save(String title, String length) throws Exception {
		String path = "http://192.168.23.1:8080/ServerForPOST/ServletForPost";
		Map<String, String> params = new HashMap<String, String>();
		params.put("name", title);
		params.put("age", length);
		return sendPOSTRequest(path, params, "UTF-8");
	}

	private static boolean sendPOSTRequest(String path,
			Map<String, String> params, String encoding) throws Exception {
		StringBuilder sb = new StringBuilder();
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				sb.append(entry.getKey()).append("=");
				sb.append(URLEncoder.encode(entry.getValue(), encoding));
				sb.append("&");
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		byte[] data = sb.toString().getBytes();
		HttpURLConnection conn = (HttpURLConnection) new URL(path)
				.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", data.length + "");
		OutputStream outStream = conn.getOutputStream();
		outStream.write(data);
		outStream.flush();
		if (conn.getResponseCode() == 200)
			return true;
		return false;
	}
}
             (4) activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/title"
    />
    
    <EditText
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/title"
    />
    
    <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/length"
    />
    
    <EditText
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:numeric="integer"
     android:id="@+id/length"
    />
    
    <Button
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/button"
    android:onClick="save"
    />

</LinearLayout>
          (5) strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidPostMethod</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    
    <string name="title">name</string>
    <string name="length">age</string>
    <string name="button">保存</string>
    <string name="success">Succeeded to save</string>
    <string name="fail">Failed to save</string>

</resources>
          (6) AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidpostmethod"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidpostmethod.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
	 <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

        3、安卓模拟器运行结果

                eclipse的console会打印以下结果:

       


              4、手机运行结果-手机截屏

                        

              eclipse的console会打印以下结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值