通过Http协议以Get和Post方式获取服务器端文本数据
来源:互联网 发布:ps淘宝修图兼职 编辑:程序博客网 时间:2024/06/05 05:02
一:以Get方式提交文本数据
public class SendRequestService {
/**
* 获取服务端输入流
* @param path 访问路径
* @param params 访问参数
* @return
* @throws Throwable
*/
public static byte[] getRequest(String path,Map<String,String> params) throws Throwable {
//http://localhost:8080/VideoWeb/manage.do?method=save&name=liming&author=limin
StringBuffer sb=new StringBuffer();
sb.append(path);
if(params!=null){
sb.append('?');
for(Map.Entry<String, String> entry:params.entrySet()){
sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8")).append('&');
}
sb.deleteCharAt(sb.length()-1);
}
URL url=new URL(sb.toString());
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();
return StreamTool.readInStream(inStream);
}else{
throw new Exception("读取失败");
}
}
二:以Post方式提交
public static byte[] sendPostRequest(String path, Map<String, String> params, String encode) throws Throwable{
// method=save&name=liming&author=324
StringBuilder sb = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=')
.append(URLEncoder.encode(entry.getValue(), encode)).append('&');
}
sb.deleteCharAt(sb.length() - 1);
}
byte[] entitydata = sb.toString().getBytes();//得到实体数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);//允许对外输出实体数据,如果采用post方式发送请求参数,必须设置为true
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(entitydata);
outStream.flush();
if(conn.getResponseCode()==200){
return StreamTool.readInStream(conn.getInputStream());
}else{
throw new Exception("请求失败");
}
}
}
三:Activity
public class UploadActivity extends Activity {
/** Called when the activity is first created. */
private TextView nameText;
private TextView authorText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button=(Button) this.findViewById(R.id.button);
nameText=(TextView) this.findViewById(R.id.name);
authorText=(TextView) this.findViewById(R.id.author);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String path="http://192.168.8.103:8080/VideoWeb/manage.do";
String name=nameText.getText().toString();
String author=authorText.getText().toString();
//String path="http://192.168.8.103:8080/VideoWeb/manage.do";
Map<String,String> params=new HashMap<String,String>();
params.put("method","save");
params.put("name", name);
params.put("author", author);
SendRequestService service= new SendRequestService();
try {
//service.getRequest(path, params);
service.sendPostRequest(path, params, "UTF-8");
Toast.makeText(UploadActivity.this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (Throwable e) {
e.printStackTrace();
Toast.makeText(UploadActivity.this, R.string.faile, Toast.LENGTH_SHORT).show();
}
}
});
}
}
四:程序运行界面
五:乱码问题
用Get方式提交数据出现乱码解决方案:
在服务端的方法里设置编码
1,public class ManageAction extends DispatchAction {
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
VideoForm formbean=(VideoForm)form;
if(request.getMethod().equals("GET")){
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
String author = new String(request.getParameter("author").getBytes("ISO-8859-1"), "UTF-8");
System.out.println("name="+ name);
System.out.println("author="+ author);
}else{
System.out.println("name="+ formbean.getName());
System.out.println("author="+ formbean.getAuthor());
}
return mapping.findForward("result");
}
}
2,在Activity中设置url编码(标记蓝色部分)
文本用Post方式提交出现乱码在服务器端添加过滤器
/**
* Servlet Filter implementation class MyFilter
*/
public class MyFilter implements Filter {
/**
* Default constructor.
*/
public MyFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req =(HttpServletRequest)request;
req.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
- 通过Http协议以Get和Post方式获取服务器端文本数据
- http协议3---GET方式和POST方式获取表单数据举例2(统一方式获取)
- Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- Http 以post方式获取数据
- 通过jQuery以HTTP GET/POST方式调用WCF服务
- http协议2---GET方式和POST方式获取表单数据举例 1(非统一方式获取数据,比较麻烦)
- android开发学习笔记(一)分别通过GET和POST请求从服务器端获取数据
- Android 以Http协议 使用get和post方式请求站点
- [Android开发]Android之使用HTTP的get,post,HttpClient三种方式向服务器端提交文本数据
- http协议4---GET方式和POST方式获取表单数据举例3(统一方式获取,解决中文乱码问题)
- 程序使用 HTTP 协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成
- .NET获取聚合数据接口数据(Http协议POST和GET请求)
- HTTP请求协议 get post方法 获取数据解析
- java通过Http get post请求url获取数据
- 通过Http协议获取文本
- http协议的get和post方式的区别
- Eclipse CDT: Disabled build settings (Windows)
- ECshop会员添加权限的开发教程
- Mac OS Mail 乱码
- 苹果消息推送服务教程:第三部分
- vmware下linux与宿主机的网络连接理解
- 通过Http协议以Get和Post方式获取服务器端文本数据
- bcb6操作word
- myeclipse启动报如下错误:java.lang.RuntimeException: No application id has been found.
- Eclipse全屏插件与颜色主题插件
- send a mail
- hdu 1071 辛普森方法
- NS2中仿真分析基于CSMA/CA的WLAN的捕获效应
- UML类图几种关系的总结
- 字符识别中的图像归一化算法