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;
     }
 
}

HttpClient是Java中的一个开源库,用于支持HTTP协议的客户端编程。它是一个用于发送HTTP请求和接收HTTP响应的包装工具类。HttpClient可以被用于执行GET和POST请求等HTTP方法。走看看是一个基于Web的应用程序,包含了各种常见的网站功能,如搜索、资讯、体育、财经、购物等多个频道。下面将分别介绍HttpClient发送GET和POST请求时的一些重要知识点。 HttpClient发送GET请求时,需要构造一个HttpGet对象,并指定请求的URL。调用HttpClient.execute方法,并且将HttpGet对象传递给该方法。接下来,HttpClient发送GET请求到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 HttpClient发送POST请求时,需要首先构造一个HttpPost对象,并指定请求的URL。调用HttpPost.setEntity方法来设置请求体内容,然后调用HttpClient.execute方法,并将HttpPost对象传递给该方法。接下来,HttpClient会将POST请求数据发送到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。与GET请求相似,可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 总的来说,HttpClient是一个十分强大和方便的网络编程工具类,可以方便地实现HTTP请求响应的处理。可以根据自己的需求选择GET和POST请求发送,然后获取响应内容和各种信息。使用HttpClient能够简化开发,提高编程效率,是Java网络编程开发中非常重要的一种库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值