一、Get提交方式
DefaultHttpClient httpclient = new DefaultHttpClient(); try { //注:如果参数值为中文的话,提交过去后可能会是乱码 HttpGet httpget = new HttpGet("http://www.xxx.com/x.jsp?username=zhangsan&age=20"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); //如果entity是流数据则关闭之 EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
二、Form表单Post提交方式
DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpost = new HttpPost("http://www.xxx.com/x.jsp?"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); //提交两个参数及值 nvps.add(new BasicNameValuePair("age", "20")); nvps.add(new BasicNameValuePair("username", "张三")); //设置表单提交编码为UTF-8 httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
在提交到的x.jsp中,我们还是像平常获取一个form表单数据那样处理就行了:
String username = request.getParameter("username");
时间: 2024-10-13 23:07:24