背景

  java程序中有时需要我们发起http级别的请求,例如抓数据或者第三方对接时,一般分为两种:一种是只需我们发起请求,还有一种是我们不但要发起请求,还要拿到请求后的数据来进行下一步处理

实现

  针对以上两种情况我们来给出简单的实现,对于在技术实现上一般分为两类:通过HttpClient方式和通过流的形式:

  • 只发送get请求
    • 通过httpclient方式 
public static String httpGet(String url, String charset)
throws HttpException, IOException {
String json = null;
HttpGet httpGet = new HttpGet();
// 设置参数
try {
httpGet.setURI(new URI(url));
} catch (URISyntaxException e) {
throw new HttpException("请求url格式错误。"+e.getMessage());
}
// 发送请求
HttpResponse httpResponse = client.execute(httpGet);
// 获取返回的数据
HttpEntity entity = httpResponse.getEntity();
byte[] body = EntityUtils.toByteArray(entity);
StatusLine sL = httpResponse.getStatusLine();
int statusCode = sL.getStatusCode();
if (statusCode == 200) {
json = new String(body, charset);
entity.consumeContent();
} else {
throw new HttpException("statusCode="+statusCode);
}
return json;
    • 通过流的方式
/**
* 发送http get请求
*
* @param getUrl
* @return
*/
public String sendGetRequest(String getUrl)
{
StringBuffer sb = new StringBuffer();
InputStreamReader isr = null;
BufferedReader br = null;
try
{
URL url = new URL(getUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setAllowUserInteraction(false);
isr = new InputStreamReader(url.openStream());
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
sb.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
fileOperator.closeResources(isr, br);
}
return sb.toString();
}
}
  • 只发送get请求获取请求结果
  public static String httpGetRequest(String url, String param) {
      StringBuffer result = null;
      BufferedReader in = null;
      try {
        String urlNameString = url + "?" + param;
        System.out.println("请求url:" + urlNameString);
        URL realUrl = new URL(urlNameString);
        // 打开和URL之间的连接
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("accept", "application/json;charset=UTF-8");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立实际的连接
        connection.connect();         // 获取所有响应头字段
   Map<String, List<String>> map = connection.getHeaderFields();
  // 遍历所有的响应头字段
  for (String key : map.keySet()) {
  System.out.println(key + "--->" + map.get(key));
  }
        // 定义 BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        result = new StringBuffer();
        while ((line = in.readLine()) != null) {
        result.append(line);
        }
      } catch (Exception e) {
      logger.info("发送GET请求出现异常!" + e);
      } finally {
        //释放资源
        try {
          if (in != null) {
            in.close();
          }
        } catch (Exception e) {
          logger.info("========get请求资源释放失败========");
        }
      }
    return result.toString();
   }
  • 只发送post请求 
public static JSONObject post(String url,JSONObject jsonObject){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(jsonObject.toString(),"UTF-8");
s.setContentType("application/json");
post.setEntity(s); HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}   //main方法测试
  import org.json.JSONObject;
  import org.json.JSONTokener;
  public static void main(String[] rags) throws Exception{
    String url="http://58.132.200.41:8280/teacher/discussion/add.json?token=58e86364c2654798a25038ae22e4e4f3";
    String queryString="{\"subjectId\": 1,\"title\": \"测试讨论1\",\"sharedRange\": 1,\"type\": 1,\"same\": false,\"specialId\": 0,\"editPhone\": false,\"contents\": [\"测试讨论内容\"]}";
    //String content=httpPostWithJSON(url, queryString,"utf-8");
    JSONObject json=post(url,new JSONObject(queryString));
    System.out.println(json);
}
  • 发送post请求获取响应结果
/**

* 向指定 URL 发送POST方法的请求

*

* @param url

* 发送请求的 URL

* @param param

* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。

* @return 所代表远程资源的响应结果

*/

public static String sendPost(String url, String param) {

    PrintWriter out = null;

    BufferedReader in = null;

    String result = "";

    try {

      URL realUrl = new URL(url);

      // 打开和URL之间的连接

      URLConnection conn = realUrl.openConnection();

      // 设置通用的请求属性

      conn.setRequestProperty("accept", "*/*");

      conn.setRequestProperty("connection", "Keep-Alive");

      conn.setRequestProperty("user-agent",

      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

      // 发送POST请求必须设置如下两行

      conn.setDoOutput(true);

      conn.setDoInput(true);

      // 获取URLConnection对象对应的输出流

      out = new PrintWriter(conn.getOutputStream());

      // 发送请求参数

      out.print(param);

      // flush输出流的缓冲

      out.flush();

      // 定义BufferedReader输入流来读取URL的响应

      in = new BufferedReader(

      new InputStreamReader(conn.getInputStream()));

      String line;

      while ((line = in.readLine()) != null) {

        result += line;

      }

  } catch (Exception e) {

    System.out.println("发送 POST 请求出现异常!"+e);

  e.printStackTrace();

  }

      //使用finally块来关闭输出流、输入流

  finally{

    try{

      if(out!=null){

        out.close();

      }

      if(in!=null){

        in.close();

      }

    }

    catch(IOException ex){

      ex.printStackTrace();

    }

  }

  return result;

  }

}

java 之程序中的http请求的更多相关文章

  1. 在 Java 应用程序中使用 Elasticsearch

    如果您使用过 Apache Lucene 或 Apache Solr,就会知道它们的使用体验非常有趣.尤其在您需要扩展基于 Lucene 或 Solr 的解决方案时,您就会了解 Elasticsear ...

  2. 在Java Web程序中使用监听器可以通过以下两种方法

    之前学习了很多涉及servlet的内容,本小结我们说一下监听器,说起监听器,编过桌面程序和手机App的都不陌生,常见的套路都是拖一个控件,然后给它绑定一个监听器,即可以对该对象的事件进行监听以便发生响 ...

  3. 在Java Web程序中使用Hibernate

    在Java Web程序中使用Hibernate与普通Java程序一样.本文中将使用Servlet和JSP结合Hibernate实现数据库表的增删改查操作. Web程序中,hibernate.cfg.x ...

  4. 在 Java 应用程序中绑定 Bean 和数据

    本指南介绍了 NetBeans IDE 对 Java 应用程序中 Bean 绑定和数据绑定的支持. 要学完本教程,您需要具备以下软件和资源. 软件或资源 要求的版本 NetBeans IDE 版本 7 ...

  5. Java应用程序中的声音播放

    声音可以创造意境,触发遐想,当与虚拟图像相结合时,更加可以让整个世界充满幻觉,声音是多媒体技术的基础. 播放声音是Java对多媒体的支持一个重要部分,它支持的声音文件类型主要有: AU - (扩展名为 ...

  6. 在 Java 应用程序中加一些 Groovy 进来

    如果您一直在阅读这个系列,那么您应该已经看到有各种各样使用 Groovy 的有趣方式,Groovy 的主要优势之一就是它的生产力.Groovy 代码通常要比 Java 代码更容易编写,而且编写起来也更 ...

  7. 在并发Java应用程序中检测可见性错误

    了解什么是可见性错误,为什么会发生,以及如何在并发Java应用程序中查找难以捉摸的可见性错误.这些问题你可能也遇到过,当在优锐课学习了一段时间后,我对这些问题有了一定见解,写下这篇文章和大家分享. 检 ...

  8. Blazor Server 应用程序中进行 HTTP 请求

    翻译自 Waqas Anwar 2021年5月4日的文章 <Making HTTP Requests in Blazor Server Apps> [1] Blazor Server 应用 ...

  9. Blazor WebAssembly 应用程序中进行 HTTP 请求

    翻译自 Waqas Anwar 2021年5月13日的文章 <Making HTTP Requests in Blazor WebAssembly Apps> [1] 在我的前篇文章< ...

随机推荐

  1. 【九天教您南方cass 9.1】 10 DTM土方计算的四种方法

    同学们大家好,欢迎收看由老王测量上班记出品的cass9.1视频课程 我是本节课主讲老师九天. 我们讲课的教程附件也是共享的,请注意索取测量空间中. [点击索取cass教程]5元立得 (给客服说暗号:“ ...

  2. 3D点云的深度学习

    使用卷积神经网络(CNN)架构的深度学习(DL)现在是解决图像分类任务的标准解决方法.但是将此用于处理3D数据时,问题变得更加复杂.首先,可以使用各种结构来表示3D数据,所述结构包括: 1  体素网格 ...

  3. Git之右键没有Git Bash Here的解决办法

    1.Win+R 打开运行输入regedit 回车打开注册表 2.找到[HKEY_CLASSES_ROOT\Directory\Background]. 3.在[Background]下如果没有[she ...

  4. Java 8 StampedLock解决同步问题

    Java 8新特性探究(十)StampedLock将是解决同步问题的新宠 JDK8中StampedLock原理探究 深入理解StampedLock及其实现原理 JDK1.8 StampedLock源码 ...

  5. QTableView 二次整理

    一.设置可视化的组件 参考: http://www.cnblogs.com/ribavnu/p/4810412.html 二.常用基本属性 http://www.cnblogs.com/ribavnu ...

  6. linux mysql卸载

    卸载mysql 1.查找以前是否装有mysql 命令:rpm -qa|grep -i mysql 可以看到mysql的包: mysql-libs-5.1.71-1.el6.x86_64 2.删除mys ...

  7. [Tensorflow] Cookbook - Retraining Existing CNNs models - Inception Model

    From: https://github.com/jcjohnson/cnn-benchmarks#alexnet 先大概了解模型,再看如果加载pre-training weight. 关于retai ...

  8. [OpenCV] Samples 18: Load image and check its attributes

    本篇内容: * 图片读取 * 图片高宽 * 图片ROI * 图片缩放 Ref: http://blog.csdn.net/u012005313/article/details/51943442 官网2 ...

  9. 【GIS】Vue、Leaflet、highlightmarker、bouncemarker

    感谢: https://github.com/brandonxiang/leaflet.marker.highlight https://github.com/maximeh/leaflet.boun ...

  10. nginx的80端口跳转到443

    然后在80端口设置http跳转到https 在80端口location中加入rewrite ^(.*)$ https://$host$1 permanent; 如图,然后输入命令service ngi ...