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



效果如下圖所示:

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

 

佈局main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?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

1
2
3
4
5
6
7
8
9
10
11
<?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>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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();
        }
 
    }
 
}



 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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請求

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
    }
}


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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("開始過濾");
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
    }
 
}

發佈了136 篇原創文章 · 獲贊 16 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章