get

  1. /**
  2. * 发送HttpGet请求
  3. * @param url
  4. * @return
  5. */
  6. public static String doGet(String url) {
  7. //1.获得一个httpclient对象
  8. CloseableHttpClient httpclient = HttpClients.createDefault();
  9. //2.生成一个get请求
  10. HttpGet httpget = new HttpGet(url);
  11. CloseableHttpResponse response = null;
  12. try {
  13. //3.执行get请求并返回结果
  14. response = httpclient.execute(httpget);
  15. } catch (IOException e1) {
  16. e1.printStackTrace();
  17. }
  18. String result = null;
  19. try {
  20. //4.处理结果,这里将结果返回为字符串
  21. HttpEntity entity = response.getEntity();
  22. if (entity != null) {
  23. result = EntityUtils.toString(entity);
  24. }
  25. } catch (ParseException | IOException e) {
  26. e.printStackTrace();
  27. } finally {
  28. try {
  29. response.close();
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. return result;
  35. }

post

  1. /**
  2. * 发送HttpPost请求,参数为map
  3. * @param url
  4. * @param map
  5. * @return
  6. */
  7. public static String doPost(String url, Map<String, Object> map) {
  8. CloseableHttpClient httpclient = HttpClients.createDefault();
  9. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  10. for (Map.Entry<String, Object> entry : map.entrySet()) {
  11. //给参数赋值
  12. formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
  13. }
  14. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
  15. HttpPost httppost = new HttpPost(url);
  16. httppost.setEntity(entity);
  17. CloseableHttpResponse response = null;
  18. try {
  19. response = httpclient.execute(httppost);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. HttpEntity entity1 = response.getEntity();
  24. String result = null;
  25. try {
  26. result = EntityUtils.toString(entity1);
  27. } catch (ParseException | IOException e) {
  28. e.printStackTrace();
  29. }
  30. return result;
  31. }