背景

  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. django template if return false

    如果if的参数不存在于context中就会返回false 参考:http://stackoverflow.com/questions/11107028/django-template-if-true- ...

  2. 【Python】socket模块应用

    [Socket] 本文记录了一些socket模块的简单应用,对于具体原理还没来得及深究. ■ 利用socket模块进行端口连接验证和扫描 在linux中常用nc命令来进行远端端口是否开放的验证.但是这 ...

  3. mycat 9066管理端口

    1.连接mycat 9066管理端口 命令:mysql -uroot -proot -P9066 -h127.0.0.1 -u:用户名 -p:密码 -P:端口 -h:ip地址例:linux路径切换到m ...

  4. golang获取命令行参数

    部署golang项目时难免要通过命令行来设置一些参数,那么在golang中如何操作命令行参数呢?可以使用os库和flag库. 1.golang os库获取命令行参数 os可以通过变量Args来获取命令 ...

  5. linux mysql卸载

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

  6. [Python] 01 - Number

    故事背景 一.大纲 如下,chapter4 是个概览,之后才是具体讲解. 二. 编译过程 Ref: http://www.dsf.unica.it/~fiore/LearningPython.pdf

  7. 02工厂方法模式FactoryMethod

    一.什么是工厂方法模式 工厂方法模式同样属于类的创建型模式又被称 为多态工厂模式 .工厂方法模式的意义是定义一个创建 产品对象的工厂接口,将实际创建工作推迟到子类当中. 核心工厂类不再负责产品的创建, ...

  8. Unity UI相关总结

    UIGrid 加载面板时,如果面板中含有大容量的 UIGrid,可能会很卡.我们可以只加载 UIGrid 的前 n 个单元格对象,在显示面板之后,利用协程加载剩余的所有单元格,每帧加载 m 个. 同样 ...

  9. Oracle中add_months()函数的用法

    查询当前时间1个月以前的时间: select add_months(sysdate,-1) from dual; 查询当前时间1个月以后的时间: select add_months(sysdate,1 ...

  10. Elasticsearch 学习之携程机票ElasticSearch集群运维驯服记(强烈推荐)

    转自: https://mp.weixin.qq.com/s/wmSTyIGCVhItVNPHcH7nsA 一.整体架构 为什么采用ES作为搜索引擎呢?在做任何事情的时候,不要一上来就急着了解怎么做这 ...