Android發送GET和POST以及HttpClient發送POST請求給服務器響應

jopen 11年前發布 | 64K 次閱讀 Android Android開發 移動開發

效果如下圖所示:

Android發送GET和POST以及HttpClient發送POST請求給服務器響應

 

布局main.xml

<?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:numeric="integer"
    android:text="@string/timelength"
    />
    <EditText  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/timelength"
    />
    <Button android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/button"
    android:onClick="save"
    android:id="@+id/button"/>
</LinearLayout>

 

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">資訊管理</string>
    <string name="title">標題</string>
    <string name="timelength">時長</string>
    <string name="button">保存</string>
    <string name="success">保存成功</string>
    <string name="fail">保存失敗</string>
    <string name="error">服務器響應錯誤</string>
</resources>

 

package cn.roco.manage;

import cn.roco.manage.service.NewsService;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText titleText;
    private EditText lengthText;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        titleText = (EditText) this.findViewById(R.id.title);
        lengthText = (EditText) this.findViewById(R.id.timelength);
    }

    public void save(View v) {
        String title = titleText.getText().toString();
        String length = lengthText.getText().toString();
        String path = "http://192.168.1.100:8080/Hello/ManageServlet";
        boolean result;
        try {
//          result = NewsService.save(path, title, length, NewsService.GET);  //發送GET請求
//          result = NewsService.save(path, title, length, NewsService.POST); //發送POST請求
            result = NewsService.save(path, title, length, NewsService.HttpClientPost); //通過HttpClient框架發送POST請求
            if (result) {
                Toast.makeText(getApplicationContext(), R.string.success, 1)
                        .show();
            } else {
                Toast.makeText(getApplicationContext(), R.string.fail, 1)
                        .show();
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
            Toast.makeText(getApplicationContext(), R.string.error, 1).show();
        }

    }

}



 

package cn.roco.manage.service;

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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class NewsService {

    public static final int POST = 1;
    public static final int GET = 2;
    public static final int HttpClientPost = 3;

    /**
     * 保存數據
     * 
     * @param title
     *            標題
     * @param length
     *            時長
     * @param flag
     *            true則使用POST請求 false使用GET請求
     * @return 是否保存成功
     * @throws Exception
     */
    public static boolean save(String path, String title, String timelength,
            int flag) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("title", title);
        params.put("timelength", timelength);
        switch (flag) {
        case POST:
            return sendPOSTRequest(path, params, "UTF-8");
        case GET:
            return sendGETRequest(path, params, "UTF-8");
        case HttpClientPost:
            return sendHttpClientPOSTRequest(path, params, "UTF-8");
        }
        return false;
    }

    /**
     * 通過HttpClient框架發送POST請求
     * HttpClient該框架已經集成在android開發包中
     * 個人認為此框架封裝了很多的工具類,性能比不上自己手寫的下面兩個方法
     * 但是該方法可以提高程序員的開發速度,降低開發難度
     * @param path
     *            請求路徑
     * @param params
     *            請求參數
     * @param encoding
     *            編碼
     * @return 請求是否成功
     * @throws Exception
     */
    private static boolean sendHttpClientPOSTRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放請求參數
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                //BasicNameValuePair實現了NameValuePair接口
                pairs.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);    //pairs:請求參數   encoding:編碼方式
        HttpPost httpPost = new HttpPost(path); //path:請求路徑
        httpPost.setEntity(entity); 

        DefaultHttpClient client = new DefaultHttpClient(); //相當于瀏覽器
        HttpResponse response = client.execute(httpPost);  //相當于執行POST請求
        //取得狀態行中的狀態碼
        if (response.getStatusLine().getStatusCode() == 200) {
            return true;
        }
        return false;
    }

    /**
     * 發送POST請求
     * 
     * @param path
     *            請求路徑
     * @param params
     *            請求參數
     * @param encoding
     *            編碼
     * @return 請求是否成功
     * @throws Exception
     */
    private static boolean sendPOSTRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        StringBuilder data = new StringBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                data.append(entry.getKey()).append("=");
                data.append(URLEncoder.encode(entry.getValue(), encoding));// 編碼
                data.append('&');
            }
            data.deleteCharAt(data.length() - 1);
        }
        byte[] entity = data.toString().getBytes(); // 得到實體數據
        HttpURLConnection connection = (HttpURLConnection) new URL(path)
                .openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length",
                String.valueOf(entity.length));

        connection.setDoOutput(true);// 允許對外輸出數據
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(entity);

        if (connection.getResponseCode() == 200) {
            return true;
        }
        return false;
    }

    /**
     * 發送GET請求
     * 
     * @param path
     *            請求路徑
     * @param params
     *            請求參數
     * @param encoding
     *            編碼
     * @return 請求是否成功
     * @throws Exception
     */
    private static boolean sendGETRequest(String path,
            Map<String, String> params, String encoding) throws Exception {
        StringBuilder url = new StringBuilder(path);
        url.append("?");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            url.append(entry.getKey()).append("=");
            url.append(URLEncoder.encode(entry.getValue(), encoding));// 編碼
            url.append('&');
        }
        url.deleteCharAt(url.length() - 1);
        HttpURLConnection connection = (HttpURLConnection) new URL(
                url.toString()).openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            return true;
        }
        return false;
    }
}


 在服務器上寫一個ManageServlet用來處理POST和GET請求

 

package cn.roco.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ManageServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String title = request.getParameter("title");
        String timelength = request.getParameter("timelength");
        System.out.println("視頻名稱:" + title);
        System.out.println("視頻時長:" + timelength);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


為了處理編碼問題 寫了過濾器

package cn.roco.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class EncodingFilter implements Filter {

    public void destroy() {
        System.out.println("過濾完成");
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        if ("GET".equals(request.getMethod())) {
            EncodingHttpServletRequest wrapper=new EncodingHttpServletRequest(request);
            chain.doFilter(wrapper, resp);
        }else{
            req.setCharacterEncoding("UTF-8");
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig fConfig) throws ServletException {
        System.out.println("開始過濾");
    }

}

package cn.roco.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * 包裝 HttpServletRequest對象
 */
public class EncodingHttpServletRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;

    public EncodingHttpServletRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name) {
        String value = request.getParameter(name);
        if (value != null && !("".equals(value))) {
            try {
                value=new String(value.getBytes("ISO8859-1"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

}


 

 


 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!