Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 通過GET和POST方式提交參數給web應用

Android 通過GET和POST方式提交參數給web應用

編輯:關於Android編程

如何把數據上傳到web應用
應用界面:
視頻名稱:title
時長:timelength
保存,點擊保存按鈕提交到web應用中,web應用中開發Manageservlet來接收數據。
get方式
服務端:
public class ManageServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOExceptionprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
String title = request.getParameter("title");
title = new String(title.getBytes("ISO8859-1"),"UTF-8");
String timelength = request.getParameter("timelength");
System.out.println("視頻名稱:"+title);
System.out.println("時長:"+timelength);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{

}
}


Android端
public class MainActivity extends Activity
{
private EditText titleText;
private EditText lengthText;
public void onCreate(Bundle savedInstance)
{
super.onCreate(Bundle savedInstance);
setContentView(R.layout.main);
titleText =(EditText)this.findViewById(R.id.title);
lengthText =(EditText)this.findViewById(R.id.timelength);
Button saveButton=(Button) this.findViewById(R.id.button);
saveButton.setOnClickListener(new ButtonClickListener());
}
private static class ButtonClickListener implements View.OnClickListener
{
public void onClick(View v)
{
String title = titleText.getText().toString();
String length = lengthText.getText().toString();
boolean result = NewsService.save(title,length);
if(result)
{
Toast.makeText(getApplicationContext(),R.string.success,1).show();
}else{
Toast.makeText(getApplicationContext(),R.string.error,1).show();
}
}
}
}


/*保存數據*/
數據通過HTTP協議提交到網絡上的web應用get post提交參數,對於2K以下的數據都可以,2K以上的必須使用post。使用get方法需要把參數把附加在路徑上




public class NewsService
{
public static boolean save(String title,String length)
{
String path = "http://192.168.1.100:8080/web/ManageServlet";
Map params = new HashMap();
params.put(("title",title);
params.put("timelength",length);
try
{
return sendGETRequest(path,params,"UTF-8");
} catch(Exception e)
{
e.printStackTrace();
}
return false;
}
/*發送get請求*/
private static boolean sendGETRequest(String path,Map params,String ecoding) throws Exception
{
//http://192.168.1.100:8080/web/ManageServlet?title=xxx&timelength=90
StringBuilder url=new StringBuilder(path);
url.append("?");
for(Map.Entry entry:params.entrySet()) //迭代集合每一個元素
{
url.append(entry.getKey()).append("=");
url.append(URLEncoder.encode(entry.getValue(),ecoding));
url.append("&");
}
url.deleteCharAt(url.length()-1);
HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200)
{
return true;
}
return false;
}
}
提交中文的話產生亂碼,產生亂碼的原因:
1,在提交參數時,沒有對中文參數進行URL編碼
修改 url.append(entry.getValue);
2,Tomcat服務器默認采用的是ISO8859-1編碼得到參數值
服務端添加 title = new String(title.getBytes("ISO8859-1"),"UTF-8");


如果很多參數,轉換很麻煩,可以采用過濾器,不用進行轉碼了
新建filter:EncodingFilter
對所有路徑進行過濾,可以修改URL Pattern /Servlet Name為 /*
public class EncodingFilter implements Filter
{
public void destroy() {}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException //每次請求到來的時候會調用該方法
{
HttpServletRequest req=(HttpServletRequest) request;
if("GET".equals(req.getMethod()))
{
EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(req);
chain.doFilter(wrapper,response);
} else {
req.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}


}
public void init(FilterConfig fConfig) thhrows ServletException{}

}
新建類 EncodingHttpServletRequest
public class EncodingHttpServletRequest extends HttpServletRequestWrapper
{
private HttpServletRequest request;
public EncodingHttpServletRequest(HttpServletRequest request)
{
super(request);
this.request=request;
}
//勾選重寫getParameter方法 @Override
public String getParameter(String name)
{
String value = request.getParameter(name);
if(value !=null)
{
try{
value = new String(value.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e)
{}
}
return value;
}
}






POST方式
Http協議介紹
POST /web/ManageServlet HTTP/1.1 方式/路徑/版本
Accept 可接收的數據類型
Referer http://192.168.1.100:8080/web/index.jsp 來源路徑
Accept-Language
User-Agent 那個廠商浏覽器
Content-Type:用於指定提取數據的內容類型 application/x-www-form-urlencoded
Accept-Encoding:
Host:192.168.1.100;8080
Content-Length:用於指定提取數據的總長度26
Connection:Keep-Alive




title=liming&timelength=90 提取數據


服務端:
public class ManageServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOExceptionprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
String title = request.getParameter("title");
//title = new String(title.getBytes("ISO8859-1"),"UTF-8");
String timelength = request.getParameter("timelength");
System.out.println("視頻名稱:"+title);
System.out.println("時長:"+timelength);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{

}
}


Android端
public class MainActivity extends Activity
{
private EditText titleText;
private EditText lengthText;
public void onCreate(Bundle savedInstance)
{
super.onCreate(Bundle savedInstance);
setContentView(R.layout.main);
titleText =(EditText)this.findViewById(R.id.title);
lengthText =(EditText)this.findViewById(R.id.timelength);
Button saveButton=(Button) this.findViewById(R.id.button);
saveButton.setOnClickListener(new ButtonClickListener());
}
private static class ButtonClickListener implements View.OnClickListener
{
public void onClick(View v)
{
String title = titleText.getText().toString();
String length = lengthText.getText().toString();
boolean result = NewsService.save(title,length);
if(result)
{
Toast.makeText(getApplicationContext(),R.string.success,1).show();
}else{
Toast.makeText(getApplicationContext(),R.string.error,1).show();
}
}
}
}


/*保存數據*/
數據通過HTTP協議提交到網絡上的web應用get post提交參數,對於2K以下的數據都可以,2K以上的必須使用post。使用get方法需要把參數把附加在路徑上




public class NewsService
{
public static boolean save(String title,String length)
{
String path = "http://192.168.1.100:8080/web/ManageServlet";
Map params = new HashMap();
params.put(("title",title);
params.put("timelength",length);
try
{
return sendPOSTRequest(path,params,"UTF-8");
} catch(Exception e)
{
e.printStackTrace();
}
return false;
}
/*發送POST請求*/
private static boolean sendPOSTRequest(String path,Map params,String ecoding) throws Exception
{
// title=liming&timelength=90
StringBuilder data=new StringBuilder();
if(params!=null && !params.isEmpty())
{
for(Map.Entryentry:params.entrySet()) //迭代集合每一個元素
{
data.append(entry.getKey()).append("=");
data.append(URLEncoder.encode(entry.getValue(),ecoding));
data.append(entry.getKey()).append("&");
}
data.deleteCharAt(data.length() - 1);
}
byte[] entity = data.toString().getBytes(); //默認采用UTF-8得到字節數據
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",String.valueOf(entity.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(entity); //數據並沒有寫入web應用,只是輸出到緩存,只有獲得響應碼後才輸出到web應用
if(conn.getResponseCode() ==200)
{
return true;
}

return false;
}

Android HttpClient框架
可以完成浏覽器完成的功能
public class NewsService
{
public static boolean save(String title,String length)
{
String path = "http://192.168.1.100:8080/web/ManageServlet";
Map params = new HashMap();
params.put(("title",title);
params.put("timelength",length);
try
{
return sendHttpClientPOSTRequest(path,params,"UTF-8");
} catch(Exception e)
{
e.printStackTrace();
}
return false;
}
/*發送POST請求*/
private static boolean sendHttpClientPOSTRequest(String path,Map params,String ecoding) throws Exception
{
List pairs = new ArrayList(); //存放請求參數
if(params !=null && !=params.isEmpty())
{
for(Map.Entry entry : params.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));

}
}
// title=liming&timelength=90
UrlEncodingFormEntity entity = new UrlEncodingFormEntity(pairs,encoding);
HttpPost httpPost=new HttpPost(path);
httpPost.setEntity(entity);
DefaultHttpClient client = new DefaultHttpClient();
client.execute(httpPost);
HttpResponse response = client.execute(httpPost);
if( response.getStatusLine().getStatusCode() ==200)
{
return true;
}
return false;
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved