java的http通信

使用URLConnection与httpClient发送get/post请求


使用URLConnection实现GET/POST请求

  1. 实例化一个java.net.URL对象;
  2. 通过URL对象的openConnection()方法得到一个java.net.URLConnection;
  3. 通过URLConnection对象的getInputStream()方法获得输入流;
  4. 读取输入流;
  5. 关闭资源
//GET
public void get() throws Exception{

    URL url = new URL("http://127.0.0.1/http/test?name=neeson&age=10");
    URLConnection urlConnection = url.openConnection();                                                    // 打开连接
    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");
    }

    System.out.println(sb.toString());
}
//POST
public void post() throws IOException{

    URL url = new URL("http://127.0.0.1/http/test");
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);        // 设置该连接是可以输出的
    httpURLConnection.setRequestMethod("POST"); // 设置请求方式
    httpURLConnection.setRequestProperty("charset", "utf-8");

    PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
    pw.write("name=neeson");                   // 向连接中输出数据(相当于发送数据给服务器)
    pw.write("&age=14");
    pw.flush();
    pw.close();

    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");
    }

    System.out.println(sb.toString());
}

使用httpclient进行GET/POST请求

//GET
public void httpclientGet() throws Exception{

    // 创建HttpClient对象
    HttpClient client = HttpClients.createDefault();

    // 创建GET请求(在构造器中传入URL字符串即可)
    HttpGet get = new HttpGet("http://127.0.0.1/http/test?name=admin&age=40");

    // 调用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);
}
//POST
public void httpclientPost() throws Exception{

    // 创建HttpClient对象
    HttpClient client = HttpClients.createDefault();

    // 创建POST请求
    HttpPost post = new HttpPost("http://127.0.0.1/http/test");

    // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)
    List<BasicNameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("name", "张三"));
    parameters.add(new BasicNameValuePair("age", "25"));

    // 向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);
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,306评论 19 139
  • 前言 说到HTTP协议,那必须要说说WWW了,WWW是环球信息网(World Wide Web )的缩写,也可以简...
    hfk阅读 6,798评论 1 4
  • 大量基础知识预警,大神请绕道~~ [TOC]#### 一.从HTML说起 一.从HTML说起 HTML是Hyper...
    Geeks_Liu阅读 10,516评论 0 34
  • 前言:近期在慕课网学习了慕课网课程Android中的HTTP通信,就自己总结了一下,其中参考了不少博文,感谢大家的...
    mecury阅读 6,813评论 1 10
  • 简书 賈小強转载请注明原创出处,谢谢! 线程安全的定义常常让人迷惑,搜索引擎会发现无数定义,比如: 多个线程同时执...
    賈小強阅读 1,592评论 0 0