通过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
}

}