博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpURLConnection
阅读量:4660 次
发布时间:2019-06-09

本文共 1182 字,大约阅读时间需要 3 分钟。

POST连接

URL url = new URL(apiUrl + pStr);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("POST");
   conn.setDoOutput(true);
   conn.connect();

   out = conn.getOutputStream();

   out.write(postData, 0, postData.length);
   out.flush();

   if (conn.getResponseCode() == 200) {

    int len = 0;
    byte[] buf = new byte[1024];
    in = conn.getInputStream();
    while ((len = in.read(buf)) > 0) {
     result += new String(buf, 0, len);
    }
   } else {
    result = "请求错误,code=" + conn.getResponseCode();
   }
GET连接
URL url = new URL(apiUrl);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");//POST
   conn.setDoOutput(false);//true
   conn.connect();
   String result = "";
   if (conn.getResponseCode() == 200) {
    int len = 0;
    byte[] buf = new byte[1024];
    InputStream in = conn.getInputStream();
    
    try {
     while ((len = in.read(buf)) > 0) {
      result += new String(buf, 0, len,"GBK");
     }
    } catch (Exception e) {
     Logger.error("失败code="+code,e);
    }finally{
     if(null != in){
      try {
       in.close();
      } catch (Exception e) {
       
      }finally{
       in = null;
      }
     }
    }
   }

com.alibaba.fastjson.JSON

JSONObject tmp = JSON.parseObject(result);

转载于:https://www.cnblogs.com/javaeye235/p/5753958.html

你可能感兴趣的文章
DP动态规划【专辑@AbandonZHANG】
查看>>
Android TextureView简易教程
查看>>
fatal: the remote end hung up unexpectedly
查看>>
Delphi-操作剪贴板
查看>>
hdu 1029
查看>>
Docker 容器的网络连接 & 容器互联
查看>>
吾爱专题脱壳练习----压缩壳练习之三
查看>>
LeetCode -- Palindrome Linked List
查看>>
栈应用——逆波兰式表达式的值
查看>>
vscode 快速生成html
查看>>
HTML5 全屏化操作功能
查看>>
返本求源——DOM元素的特性与属性
查看>>
4、C#进阶:MD5加密、进程、线程、GDI+、XML、委托
查看>>
部署DLL webservices 若干费脑点
查看>>
zabbix监控报错zabbix server is not running解决方法
查看>>
python面向对象实例
查看>>
java基础之 创建对象的几种方式
查看>>
[HNOI2008]明明的烦恼
查看>>
Navicat不能连接linux数据库问题
查看>>
centos7关闭防火墙
查看>>