android基础--通过http协议提交数据到web应用
2011-10-18 17:34
337 查看
通过get方式和post方式
1.建立web应用并部署在服务器上
package cn.com.servlet;
public class ManageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String timelength = request.getParameter("timelength");
System.out.println("视频标题:"+title);
System.out.println("视频时长:"+timelength);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package cn.com.service.impl;
public class VideoNewServiceImpl implements VideoNewService {
public List<News> getLastNews(){
List<News> news= new ArrayList<News>();
news.add(new News(3,"哈利波特",100));
news.add(new News(4,"music of voice",110));
news.add(new News(5,"飞跃疯人院",120));
return news;
}
}
package cn.com.request;
public class EncodeRequestWrapper extends HttpServletRequestWrapper {
private HttpServletRequest request;
public EncodeRequestWrapper(HttpServletRequest request) {
super(request);
this.request=request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
try{
if(value!=null)
return new String(value.getBytes("ISO8859-1"), "UTF-8");
}catch (Exception e) {
}
return super.getParameter(name);
}
}
package cn.com.filter;
public class EncodeFilter implements Filter {
public EncodeFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
if("GET".equals(req.getMethod())){//get
EncodeRequestWrapper wrapper = new EncodeRequestWrapper(req);
chain.doFilter(wrapper, response);
}else{//post
req.setCharacterEncoding("UTF-8");
chain.doFilter(req, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
2.android项目:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<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/timelength"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numeric="integer"
android:id="@+id/timelength"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>
package cn.com.service;
public class NewsManageService {
/**
* 保存数据
* @param title
* @param timelength
*/
public static boolean save(String title, String timelength) throws Exception{
String path = "http://192.168.1.131:8080/videonews/ManageServlet";
Map<String, String> params = new HashMap<String, String>();
params.put("title", title);
params.put("timelength", timelength);
return sendHttpClientRequest(path,params,"UTF-8");
}
/**
* 采用HttpClient发送POST请求
* 操作https和cookie时候代码量比较多,可以用httpclient框架,其他情况不建议用
* @param path请求路径
* @param params请求参数
* @throws IOException
* @throws ClientProtocolException
*/
private static boolean sendHttpClientRequest(String path,Map<String, String> params, String encoding) throws ClientProtocolException, IOException {
List<NameValuePair> param = new ArrayList<NameValuePair>();
if(param!=null&&!param.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(param);
HttpPost post = new HttpPost(path);
post.setEntity(encodedFormEntity);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode()==200){
return true;
}
return false;
}
/**
* 发送POST请求
* @param path请求路径
* @param params请求参数
*/
private static boolean sendPOSTRequest(String path,Map<String, String> params, String string)throws Exception {
StringBuilder sb = new StringBuilder();
//title=jjj&timelength=77
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), string)).append('&');
}
sb.deleteCharAt(sb.length()-1);
}
byte [] entity = sb.toString().getBytes();
HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);//允许对外输出数据
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(entity.length));
OutputStream outputStream = connection.getOutputStream();
outputStream.write(entity);
if(connection.getResponseCode()==200){
return true;
}
return false;
}
/**
* 发送GET请求
* @param path请求路径
* @param params请求参数
*/
private static boolean sendGETRequest(String path, Map<String, String> params,String encoding) throws Exception{
StringBuilder sb = new StringBuilder(path);
sb.append('?');
for(Map.Entry<String, String>entry:params.entrySet()){
sb.append(entry.getKey())
.append('=')
.append(URLEncoder.encode(entry.getValue(),encoding))
.append('&');
}
sb.deleteCharAt(sb.length()-1);
HttpURLConnection connection = (HttpURLConnection) new URL(sb.toString()).openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if(connection.getResponseCode()==200){
return true;
}
return false;
}
}package cn.com.newsmanage;
public class MainActivity extends Activity {
private EditText titleText;
private EditText timelengthText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
titleText=(EditText) this.findViewById(R.id.title);
timelengthText=(EditText) this.findViewById(R.id.timelength);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
private final class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
String title = titleText.getText().toString();
String timelength = timelengthText.getText().toString();
try {
//写一个业务类传到WEB
NewsManageService.save(title,timelength);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
e.printStackTrace();
}
}
}
}
1.建立web应用并部署在服务器上
package cn.com.servlet;
public class ManageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String timelength = request.getParameter("timelength");
System.out.println("视频标题:"+title);
System.out.println("视频时长:"+timelength);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package cn.com.service.impl;
public class VideoNewServiceImpl implements VideoNewService {
public List<News> getLastNews(){
List<News> news= new ArrayList<News>();
news.add(new News(3,"哈利波特",100));
news.add(new News(4,"music of voice",110));
news.add(new News(5,"飞跃疯人院",120));
return news;
}
}
package cn.com.request;
public class EncodeRequestWrapper extends HttpServletRequestWrapper {
private HttpServletRequest request;
public EncodeRequestWrapper(HttpServletRequest request) {
super(request);
this.request=request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
try{
if(value!=null)
return new String(value.getBytes("ISO8859-1"), "UTF-8");
}catch (Exception e) {
}
return super.getParameter(name);
}
}
package cn.com.filter;
public class EncodeFilter implements Filter {
public EncodeFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
if("GET".equals(req.getMethod())){//get
EncodeRequestWrapper wrapper = new EncodeRequestWrapper(req);
chain.doFilter(wrapper, response);
}else{//post
req.setCharacterEncoding("UTF-8");
chain.doFilter(req, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
2.android项目:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<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/timelength"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numeric="integer"
android:id="@+id/timelength"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
</LinearLayout>
package cn.com.service;
public class NewsManageService {
/**
* 保存数据
* @param title
* @param timelength
*/
public static boolean save(String title, String timelength) throws Exception{
String path = "http://192.168.1.131:8080/videonews/ManageServlet";
Map<String, String> params = new HashMap<String, String>();
params.put("title", title);
params.put("timelength", timelength);
return sendHttpClientRequest(path,params,"UTF-8");
}
/**
* 采用HttpClient发送POST请求
* 操作https和cookie时候代码量比较多,可以用httpclient框架,其他情况不建议用
* @param path请求路径
* @param params请求参数
* @throws IOException
* @throws ClientProtocolException
*/
private static boolean sendHttpClientRequest(String path,Map<String, String> params, String encoding) throws ClientProtocolException, IOException {
List<NameValuePair> param = new ArrayList<NameValuePair>();
if(param!=null&&!param.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(param);
HttpPost post = new HttpPost(path);
post.setEntity(encodedFormEntity);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode()==200){
return true;
}
return false;
}
/**
* 发送POST请求
* @param path请求路径
* @param params请求参数
*/
private static boolean sendPOSTRequest(String path,Map<String, String> params, String string)throws Exception {
StringBuilder sb = new StringBuilder();
//title=jjj&timelength=77
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), string)).append('&');
}
sb.deleteCharAt(sb.length()-1);
}
byte [] entity = sb.toString().getBytes();
HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);//允许对外输出数据
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(entity.length));
OutputStream outputStream = connection.getOutputStream();
outputStream.write(entity);
if(connection.getResponseCode()==200){
return true;
}
return false;
}
/**
* 发送GET请求
* @param path请求路径
* @param params请求参数
*/
private static boolean sendGETRequest(String path, Map<String, String> params,String encoding) throws Exception{
StringBuilder sb = new StringBuilder(path);
sb.append('?');
for(Map.Entry<String, String>entry:params.entrySet()){
sb.append(entry.getKey())
.append('=')
.append(URLEncoder.encode(entry.getValue(),encoding))
.append('&');
}
sb.deleteCharAt(sb.length()-1);
HttpURLConnection connection = (HttpURLConnection) new URL(sb.toString()).openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if(connection.getResponseCode()==200){
return true;
}
return false;
}
}package cn.com.newsmanage;
public class MainActivity extends Activity {
private EditText titleText;
private EditText timelengthText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
titleText=(EditText) this.findViewById(R.id.title);
timelengthText=(EditText) this.findViewById(R.id.timelength);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
private final class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
String title = titleText.getText().toString();
String timelength = timelengthText.getText().toString();
try {
//写一个业务类传到WEB
NewsManageService.save(title,timelength);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
e.printStackTrace();
}
}
}
}
相关文章推荐
- Android应用开发之通过HTTP协议发送XML数据并调用
- 【Android基础】通过SharedPreferences来保存数据
- Android 通过Post方式提交数据
- android中通过GET方法接收数据并通过xml解析数据,POST方法向服务器提交数据
- Android如何通过Retrofit提交Json格式数据
- android 三种通过Http 协议 提交数据方式
- Android开发入门之通过GET和POST方式提交参数给web应用
- Android通过HTTP协议实现上传文件数据
- Android通过Get方式提交数据的乱码处理
- Android应用开发中,会经常要提交数据到服务器和从服务器得到数据,本文主要是给出了利用http协议采用HttpClient方式向服务器提交数据的方法。
- Android之使用HTTP协议的Get/Post方式向服务器提交数据
- Android之使用HTTP协议的Get/Post方式向服务器提交数据
- Android通过HTTP协议实现上传文件数据
- Android通过Post与Get提交数据
- Android通过Post与Get提交数据
- Android通过http协议POST传输方式(输出流提交到服务端)
- Android 通过GET和POST方式提交参数给web应用
- Android 通过Get/Post提交请求数据到服务器
- Android之通过HTTP协议向服务器发送XML数据
- android 通过get,post方式提交数据给服务器