实现代码:
package test.util; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Map.Entry; /** * * @author junhu * */ public class HttpUtil { /** * 使用URLConnection实现GET请求 * * 1.实例化一个java.net.URL对象; 2.通过URL对象的openConnection()方法得到一个java.net.URLConnection; * 3.通过URLConnection对象的getInputStream()方法获得输入流; 4.读取输入流; 5.关闭资源; */ public static void get(String urlStr) throws Exception { URL url = new URL(urlStr); URLConnection urlConnection = url.openConnection(); // 打开连接 System.out.println(urlConnection.getURL().toString()); BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8")); // 获取输入流 String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); System.out.println(sb.toString()); } /** * 使用HttpURLConnection实现POST请求 * * 1.实例化一个java.net.URL对象; 2.通过URL对象的openConnection()方法得到一个java.net.URLConnection; * 3.通过URLConnection对象的getOutputStream()方法获得输出流; 4.向输出流中写数据; 5.关闭资源; */ public static void post(String urlStr, Map<String, String> parameterMap) throws IOException { URL url = new URL(urlStr); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); // 设置该连接是可以输出的 httpURLConnection.setRequestMethod("POST"); // 设置请求方式 httpURLConnection.setRequestProperty("charset", "utf-8"); System.out.println(httpURLConnection.getURL().toString()); PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream())); StringBuffer parameter = new StringBuffer(); parameter.append("1=1"); for (Entry<String, String> entry : parameterMap.entrySet()) { parameter.append("&" + entry.getKey() + "=" + entry.getValue()); } pw.write(parameter.toString());// 向连接中写数据(相当于发送数据给服务器) pw.flush(); pw.close(); System.out.println("parameter: " + parameter.toString()); BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8")); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { // 读取数据 sb.append(line + "\n"); } br.close(); System.out.println(sb.toString()); } }
测试代码:
package test.http; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import test.util.HttpClientUtil; /** * http通信测试 * * @author junhu */ public class TestHttp { public static void main(String[] args) { try { // --------------测试请求/test/index begin--------------------------- // HttpUtil.get("http://localhost:8080/Java_http/test/index?name=zhangsan&age=22&sex=nan"); // Map<String, String> parameterMap = new HashMap<String, String>(); // parameterMap.put("name", "zhangsan"); // parameterMap.put("age", "22"); // parameterMap.put("sex", "nan"); // HttpUtil.post("http://localhost:8080/Java_http/test/index", parameterMap); // --------------测试请求/test/index end--------------------------- // --------------测试请求/test/index2 begin--------------------------- // HttpUtil.get("http://localhost:8080/Java_http/test/index2?userName=zhangsan&userAge=22&userSex=nan"); // Map<String, String> parameterMap = new HashMap<String, String>(); // parameterMap.put("userName", "zhangsan"); // parameterMap.put("userAge", "22"); // parameterMap.put("userSex", "nan"); // HttpUtil.post("http://localhost:8080/Java_http/test/index2", parameterMap); // --------------测试请求/test/index2 end--------------------------- } catch (Exception e) { e.printStackTrace(); } } }二、使用 HttpClient实现GET和POST请求
实现代码:
package test.util; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * * @author junhu * */ public class HttpClientUtil { /** * 使用httpclient进行http通信 * * Get请求 */ public static void httpclientGet(String urlStr) throws Exception { System.out.println(urlStr); // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建GET请求(在构造器中传入URL字符串即可) HttpGet get = new HttpGet(urlStr); // 调用HttpClient对象的execute方法获得响应 HttpResponse response = client.execute(get); // 调用HttpResponse对象的getEntity方法得到响应实体 HttpEntity httpEntity = response.getEntity(); // 使用EntityUtils工具类得到响应的字符串表示 String result = EntityUtils.toString(httpEntity, "utf-8"); System.out.println(result); } /** * 使用httpclient进行http通信 * * Post请求 */ public static void httpclientPost(String urlStr, List<NameValuePair> parameters) throws Exception { System.out.println(urlStr); // 创建HttpClient对象 HttpClient client = HttpClients.createDefault(); // 创建POST请求 HttpPost post = new HttpPost(urlStr); // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)--> parameters // 向POST请求中添加消息实体 post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); // 得到响应并转化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity, "utf-8"); System.out.println(result); } }
测试代码:
package test.http; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import test.util.HttpClientUtil; /** * http通信测试 * * @author junhu */ public class TestHttp { public static void main(String[] args) { try { // --------------测试请求/test/index begin--------------------------- // HttpClientUtil // .httpclientGet("http://localhost:8080/Java_http/test/index?name=zhangsan&age=22&sex=nan"); // List<NameValuePair> parameters = new ArrayList<NameValuePair>(); // parameters.add(new BasicNameValuePair("name", "zhangsan")); // parameters.add(new BasicNameValuePair("age", "22")); // parameters.add(new BasicNameValuePair("sex", "nan")); // HttpClientUtil.httpclientPost("http://localhost:8080/Java_http/test/index", parameters); // --------------测试请求/test/index end--------------------------- // --------------测试请求/test/index2 begin--------------------------- // HttpClientUtil // .httpclientGet("http://localhost:8080/Java_http/test/index2?userName=zhangsan&userAge=22&userSex=nan"); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("userName", "zhangsan")); parameters.add(new BasicNameValuePair("userAge", "22")); parameters.add(new BasicNameValuePair("userSex", "nan")); HttpClientUtil.httpclientPost("http://localhost:8080/Java_http/test/index2", parameters); // --------------测试请求/test/index2 end--------------------------- } catch (Exception e) { e.printStackTrace(); } } }三、模拟POST请求发送JSON参数
实现测试代码:
package test.http; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class TestHttpWithJSON { public static void httpPostWithJSON(String url, String json) { // 创建默认的httpClient实例 CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 创建httppost HttpPost httppost = new HttpPost(url); httppost.addHeader("Content-type", "application/json; charset=utf-8"); System.out.println("executing request " + httppost.getURI()); // 向POST请求中添加消息实体 StringEntity se = new StringEntity(json, "UTF-8"); httppost.setEntity(se); System.out.println("request parameters " + json); // 执行post请求 CloseableHttpResponse response = httpclient.execute(httppost); try { // 获取响应实体 HttpEntity entity = response.getEntity(); // 打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { // 打印响应内容 System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (Exception e) { System.out.println("executing httpPostWithJSON error: " + e.getMessage()); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { System.out.println("executing httpPostWithJSON error: " + e.getMessage()); } } } public static void main(String[] args) { // JsonObject jsonObject = new JsonObject(); // jsonObject.addProperty("userName", "张三"); // jsonObject.addProperty("userAge", "22"); // jsonObject.addProperty("userSex", "男"); // String url = "http://localhost:8080/Java_http/test/index3"; // httpPostWithJSON(url, jsonObject.toString()); String url = "http://localhost:8080/Java_http/test/index3"; String json = "{\"userName\":\"张三\",\"userAge\":\"22\",\"userSex\":\"男\"}"; httpPostWithJSON(url, json); } }四、以下是公共的处理请求的代码(控制器)
package test.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import test.bean.User; /** * @author junhu */ @Controller @RequestMapping("/test") public class TestController { @RequestMapping(value = "/index", method = RequestMethod.GET) public String testGet(HttpServletRequest request, HttpServletResponse response) { System.out.println(request.getParameter("name")); System.out.println(request.getParameter("age")); System.out.println(request.getParameter("sex")); return "success"; } @RequestMapping(value = "/index", method = RequestMethod.POST) public String testPost(HttpServletRequest request, HttpServletResponse response) { System.out.println(request.getParameter("name")); System.out.println(request.getParameter("age")); System.out.println(request.getParameter("sex")); return "success"; } @RequestMapping(value = "/index2", method = RequestMethod.GET) public String testGetByObject(@ModelAttribute("user") User user, Model model) { System.out.println(user.getUserName()); System.out.println(user.getUserAge()); System.out.println(user.getUserSex()); return "success"; } @RequestMapping(value = "/index2", method = RequestMethod.POST) public String testPostByObject(@ModelAttribute("user") User user, Model model) { System.out.println(user.getUserName()); System.out.println(user.getUserAge()); System.out.println(user.getUserSex()); return "success"; } @RequestMapping(value = "/index3", method = RequestMethod.POST) public @ResponseBody User testPostByJson(@RequestBody User user, Model model) { System.out.println(user.getUserName()); System.out.println(user.getUserAge()); System.out.println(user.getUserSex()); return user; } }
转载请注明出处:http://xieke90.iteye.com/blog/2259953