用java代码实现GET请求
转载自:传智播客教程
客户端
/** * GET请求 * * @param path * @param params * @param enc * @return * @throws Exception */ public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{ StringBuilder sb = new StringBuilder(path); sb.append('?'); // ?method=save&title=435435435&timelength=89& for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), enc)).append('&'); } sb.deleteCharAt(sb.length()-1); URL url = new URL(sb.toString()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); if(conn.getResponseCode()==200){ return true; } return false; }
服务端使用struts:
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { VideoForm formbean = (VideoForm)form; if("GET".equals(request.getMethod())){ byte[] data = request.getParameter("title").getBytes("ISO-8859-1"); String title = new String(data, "UTF-8"); System.out.println("title:"+ title); System.out.println("timelength:"+ formbean.getTimelength()); }else{ System.out.println("title:"+ formbean.getTitle()); System.out.println("timelength:"+ formbean.getTimelength()); } return mapping.findForward("result"); }
调用示例:
Map<String, String> params = new HashMap<String, String>(); params.put("method", "save"); params.put("title", "liming"); params.put("timelength", "80"); HttpRequest.sendGetRequest("http://10.10.97.51:8180/videoweb/video/manage.do", params, "UTF-8");
浙公网安备 33010602011771号