实验:提交视频名称、时长信息
url:
http://192.168.1.102:8080/videoweb/video/manage.do?method=save&name=xxx&timelength=90
资源
< string name ="name" >视频名称 </ string >
< string name ="timeLength" >时长 </ string >
< string name ="save" >保存 </ string >
< string name ="success" >数据保存成功 </ string >
< string name ="fail" >数据保存失败 </ string >
< string name ="error" >网络连接失败 </ string >
< string name ="videoFile" >视频文件 </ string >
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:text ="@string/name" />
< EditText
android:id ="@+id/nameEt"
android:layout_width ="match_parent"
android:layout_height ="wrap_content" >
< requestFocus />
</ EditText >
< TextView
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:text ="@string/timeLength" />
< EditText
android:id ="@+id/timeLengthEt"
android:layout_width ="match_parent"
android:layout_height ="wrap_content" >
</ EditText >
< Button
android:id ="@+id/saveBtn"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="save" />
String path = "http://192.168.1.102:8080/videoweb/video/manage.do";
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("timelength", timeLength);
params.put("method", "save");
return sendPostRequestHttpClient(path, params, "UTF-8");
}
private static boolean sendPostRequestHttpClient(String path,
Map<String, String> params, String string) throws Exception {
// http://192.168.1.102 :8080/videoweb/video/manage.do?method=save&name=xxx&timelength=90
StringBuilder pathBuilder = new StringBuilder(path);
pathBuilder.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
pathBuilder.append(entry.getKey()).append("=")
.append(entry.getValue()).append("&");
}
pathBuilder.deleteCharAt(pathBuilder.length() - 1);
URL url = new URL(pathBuilder.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
return true;
}
return false;
}
测试方法代码
VideoServiceTest
VideoService.save("Sucan", "80");
}
中文字符解决方案:
服务器端代码:
if("GET".equals(request.getMethod())){
String name = new String(request.getParameter("name")
.getBytes("ISO8859-1"),"UTF-8");
System.out.println("视频名称: "+ name);
System.out.println("时长: "+formbean.getTimelength());
} else{
System.out.println("视频名称: "+formbean.getName());
System.out.println("时长: "+formbean.getTimelength());
}
客户端的VideoService中
POST方式
修改服务器端代码
Index.jsp
method ="post" >
< input type ="hidden" name ="method" value ="save" >< br />
视频名称: < input type ="text" name ="name" value ="" >< br />
时长: < input type ="text" name ="timelength" value ="" >< br />
< input type ="submit" value ="提交" >
</ form >
Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Referer: http://192.168.1.102:8080/videoweb/
Accept-Language: zh-cn,en-GB ; q=0.5
User-Agent: Mozilla/4.0 (compatible ; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 192.168.1.102:8080
Content-Length: 34
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: JSESSIONID=AE51607F874103B085624AD38C68CF56
method=save&name=xxxx&timelength=2
Map<String, String> params, String encoding) throws Exception {
/*
* Content-Type: application/x-www-form-urlencoded
* Content-Length: 34
* method=save&name=xxxx&timelength=2
*/
StringBuffer sb = new StringBuffer("");
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=")
// .append(entry.getValue()).append("&");
.append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); // url编码,解决中文乱码
}
sb.deleteCharAt(sb.length() - 1);
}
byte[] data = sb.toString().getBytes(); // 得到实体数据eg. method=save&name=xxxx&timelength=2
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setDoOutput( true); // 允许通过POST方式提交数据,必须允许输出
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if (conn.getResponseCode() == 200) {
return true;
}
return false;
}
return sendPostRequest(path, params, "UTF-8");
运行客户端,测试代码,查看服务器后台打印
解释Post方式下中文乱码的处理:服务器端增加过滤器
HttpClient
简介
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.1.1
HttpClient 功能介绍
以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。
(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
实验步骤
在VideoService中添加方法sendRequestHttpClient
private static boolean sendRequestHttpClient(String path,
Map<String, String> params, String encoding) throws Exception {
List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
if(params!= null && !params.isEmpty()){
for(Map.Entry<String, String> entry: params.entrySet()){
BasicNameValuePair param = new BasicNameValuePair(entry.getKey(),entry.getValue());
paramPairs.add(param);
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramPairs, encoding);
HttpPost post = new HttpPost(path);
post.setEntity(entity);
DefaultHttpClient client = new DefaultHttpClient(); // 浏览器
HttpResponse response = client.execute(post);
/*
* HTTP/1.1 200 OK
* Server: Apache-Coyote/1.1
* Content-Type: text/html;charset=UTF-8
* Content-Length: 14
* Date: Thu, 22 Dec 2011 15:07:38 GMT
*
*淇濆瓨鎴愬
* */
if(response.getStatusLine().getStatusCode() == 200){
return true;
}
return false;
}
// return sendPostRequest(path, params, "UTF-8");
return sendRequestHttpClient(path, params, "UTF-8");