Java如何实现URL带请求参数(get/post)及得到get和post请求url和参数列表的方法
具体代码如下所示:
publicstaticStringsendGet(Stringurl,Stringparam) { Stringresult=""; try{ StringurlName=url+"?"+param;// URLU=newURL(urlName); URLConnectionconnection=U.openConnection(); connection.connect(); BufferedReaderin=newBufferedReader(newInputStreamReader(connection.getInputStream())); Stringline; while((line=in.readLine())!=null) { result+=line; } in.close(); }catch(Exceptione){ System.out.println("Helloword!!"+e); } returnresult; } publicstaticStringsendPost(Stringurl,Stringparam) { Stringresult=""; try{ URLhttpurl=newURL(url); HttpURLConnectionhttpConn=(HttpURLConnection)httpurl.openConnection(); httpConn.setDoOutput(true); httpConn.setDoInput(true); PrintWriterout=newPrintWriter(httpConn.getOutputStream()); out.print(param); out.flush(); out.close(); BufferedReaderin=newBufferedReader(newInputStreamReader(httpConn.getInputStream())); Stringline; while((line=in.readLine())!=null) { result+=line; } in.close(); }catch(Exceptione){ System.out.println("Helloword!"+e); } returnresult; }
下面给大家介绍 java得到GET和POST请求URL和参数列表的方法
在servlet中GET请求可以通过HttpServletRequest的getRequestURL方法和getQueryString()得到完整的请求路径和请求所有参数列表,POST的需要getParameterMap()方法遍历得到,不论GET或POST都可以通过getRequestURL+getParameterMap()来得到请求完整路径
packagecom.zuidaima importjava.io.IOException; importjava.io.PrintWriter; importjava.util.Map; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassGetParamsextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L; publicGetParams(){ super(); } protectedvoiddoGet(HttpServletRequestrequest, HttpServletResponseresponse)throwsServletException,IOException{ PrintWriterwriter=response.getWriter(); writer.println("GET"+request.getRequestURL()+"" +request.getQueryString()); Map<String,String[]>params=request.getParameterMap(); StringqueryString=""; for(Stringkey:params.keySet()){ String[]values=params.get(key); for(inti=0;i<values.length;i++){ Stringvalue=values[i]; queryString+=key+"="+value+"&"; } } //去掉最后一个空格 queryString=queryString.substring(0,queryString.length()-1); writer.println("GET"+request.getRequestURL()+""+queryString); } protectedvoiddoPost(HttpServletRequestrequest, HttpServletResponseresponse)throwsServletException,IOException{ PrintWriterwriter=response.getWriter(); Map<String,String[]>params=request.getParameterMap(); StringqueryString=""; for(Stringkey:params.keySet()){ String[]values=params.get(key); for(inti=0;i<values.length;i++){ Stringvalue=values[i]; queryString+=key+"="+value+"&"; } } //去掉最后一个空格 queryString=queryString.substring(0,queryString.length()-1); writer.println("POST"+request.getRequestURL()+""+queryString); } }
以上代码简单易懂,希望对大家学习javapostgeturl请求参数的相关方法有所帮助,感谢大家一直以来对毛票票网站的支持,有你们的支持,我们会做的更好。