android基础--通过http协议提交数据到web应用

来源:互联网 发布:非诚勿扰网络作家梦瑶 编辑:程序博客网 时间:2024/05/13 17:27
 

通过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();

                     }

              }

             

       }

}