Android GET,POST向伺服器端傳送資料(傳送)
阿新 • • 發佈:2019-01-08
//目錄結構
//strings.xml字元常量檔案
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="title">通過Get和Post兩種方式分別提交資料到伺服器</string>
- <string name="app_name">GetAndPostRequest</string>
- <string name="book_name">書本名稱</string>
- <string name
- <string name="success">提交成功</string>
- <string name="error">提交失敗</string>
- <string name="get_request">Get請求提交</string>
- <string name="post_request">Post請求提交</string>
- </resources>
- <?
- <LinearLayout ="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height
- android:text="@string/title" />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/book_name"
- />
- <EditText
- android:id="@+id/book_name"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/book_price"
- />
- <EditText
- android:id="@+id/book_price"
- android:numeric="integer"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <LinearLayout
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- >
- <Button
- android:id="@+id/get_reqeust"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/get_request"
- />
- <Button
- android:id="@+id/post_reqeust"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/post_request"
- />
- </LinearLayout>
- </LinearLayout>
- package sn.len.request;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.Map;
- public class RequestService
- {
- //get請求,有檔案長度大小限制
- public static boolean getRequest(String urlPath) throws Exception
- {
- URL url=new URL(urlPath);
- HttpURLConnection con=(HttpURLConnection)url.openConnection();
- con.setRequestMethod("GET");
- con.setReadTimeout(5*1000);
- if(con.getResponseCode()==200)
- {
- return true;
- }
- return false;
- }
- //post請求,無檔案長度大小限制
- public static boolean postRequest(String urlPath,Map<String,String> map) throws Exception
- {
- StringBuilder builder=new StringBuilder(); //拼接字元
- //拿出鍵值
- if(map!=null && !map.isEmpty())
- {
- for(Map.Entry<String, String> param:map.entrySet())
- {
- builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(), "utf-8")).append('&');
- }
- builder.deleteCharAt(builder.length()-1);
- }
- //下面的Content-Length: 是這個URL的二進位制資料長度
- byte b[]=builder.toString().getBytes();
- URL url=new URL(urlPath);
- HttpURLConnection con=(HttpURLConnection)url.openConnection();
- con.setRequestMethod("POST");
- con.setReadTimeout(5*1000);
- con.setDoOutput(true);//打開向外輸出
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//內容型別
- con.setRequestProperty("Content-Length",String.valueOf(b.length));//長度
- OutputStream outStream=con.getOutputStream();
- outStream.write(b);//寫入資料
- outStream.flush();//重新整理記憶體
- outStream.close();
- //狀態碼是不成功
- if(con.getResponseCode()==200)
- {
- return true;
- }
- return false;
- }
- }
- package sn.len.getandpostreq;
- import java.util.HashMap;
- import java.util.Map;
- import sn.len.request.RequestService;
- import Android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.EditText;
- import android.widget.Toast;
- public class GetAndPostRequestActivity extends Activity implements OnClickListener
- {
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- View get_button=findViewById(R.id.get_reqeust);
- View post_button=findViewById(R.id.post_reqeust);
- get_button.setOnClickListener(this);
- post_button.setOnClickListener(this);
- }
- @Override
- public void onClick(View v)
- {
- EditText book_name=(EditText)findViewById(R.id.book_name);
- EditText book_price=(EditText)findViewById(R.id.book_price);
- String bookname=book_name.getText().toString();
- String bookprice=book_price.getText().toString();
- switch(v.getId())
- {
- case R.id.get_reqeust: //Get請求
- {
- //第一種可以用字串拼接
- String urlPath="http://192.168.0.133/web/index.jsp"+"?type=save&book_name="+bookname+"&book_price="+bookprice+"";
- String realPath=urlPath.replaceAll(" ", "");//把多餘的空格替換掉
- try
- {
- if(RequestService.getRequest(realPath))
- {
- Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();
- }
- }
- catch (Exception e)
- {
- Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
- e.printStackTrace();
- }
- }break;
- case R.id.post_reqeust: //Post請求
- {
- String urlPath="http://192.168.0.133/web/index.jsp";
- Map<String,String> map=new HashMap<String,String>();//用集合來做,比字串拼接來得直觀
- map.put("type", "save");
- map.put("book_name",bookname);
- map.put("book_price",bookprice);
- try
- {
- if(RequestService.postRequest(urlPath, map))
- {
- Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();
- }
- }
- catch (Exception e)
- {
- Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
- Log.e("ERRORS", e.toString());
- e.printStackTrace();
- }
- }break;
- default:break;
- }
- }
- }
- <%@page contentType="text/html" pageEncoding="GBK" language="java"%>
- <%
- String type=request.getParameter("type");
- if(type!=null && !"".equals(type))
- {
- if(type.equals("save"))
- {
- String book_name=request.getParameter("book_name");
- String book_price=request.getParameter("book_price");
- if((book_name!=null && !"".equals(book_name)) && (book_price!=null && !"".equals(book_price)))
- {
- System.out.println("書名"+book_name);
- System.out.println("價格"+book_price);
- }
- }
- }
- %>
//Tomcat服務端響應效果,書名和價格都已經打出來了。