本文共 11344 字,大约阅读时间需要 37 分钟。
http://xieke90.iteye.com/blog/2259953 一、使用URLConnection实现GET和POST请求
实现代码:
- 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;
-
-
-
-
-
-
- public class HttpUtil
- {
-
-
-
-
-
-
- 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());
- }
-
-
-
-
-
-
-
- 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;
-
-
-
-
-
-
- public class TestHttp
- {
- public static void main(String[] args)
- {
- try
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- 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;
-
-
-
-
-
-
- public class HttpClientUtil
- {
-
-
-
-
-
- public static void httpclientGet(String urlStr) throws Exception
- {
-
- System.out.println(urlStr);
-
-
- HttpClient client = HttpClients.createDefault();
-
-
- HttpGet get = new HttpGet(urlStr);
-
-
- HttpResponse response = client.execute(get);
-
-
- HttpEntity httpEntity = response.getEntity();
-
-
- String result = EntityUtils.toString(httpEntity, "utf-8");
- System.out.println(result);
- }
-
-
-
-
-
-
- public static void httpclientPost(String urlStr, List<NameValuePair> parameters) throws Exception
- {
-
- System.out.println(urlStr);
-
-
- HttpClient client = HttpClients.createDefault();
-
-
- HttpPost post = new HttpPost(urlStr);
-
-
-
-
- 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;
-
-
-
-
-
-
- public class TestHttp
- {
- public static void main(String[] args)
- {
- try
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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);
-
- }
- 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)
- {
-
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try
- {
-
- HttpPost httppost = new HttpPost(url);
- httppost.addHeader("Content-type", "application/json; charset=utf-8");
- System.out.println("executing request " + httppost.getURI());
-
-
- StringEntity se = new StringEntity(json, "UTF-8");
- httppost.setEntity(se);
- System.out.println("request parameters " + json);
-
-
- 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)
- {
-
-
-
-
-
-
-
- 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;
-
-
-
-
- @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;
- }
- }
转载请注明出处: