博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http的post请求和get请求
阅读量:7047 次
发布时间:2019-06-28

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

post

public static String post(String urlStr, String strInfo){    URL localURL;    OutputStream outputStream = null;    OutputStreamWriter outputStreamWriter = null;    InputStream inputStream = null;    InputStreamReader inputStreamReader = null;    BufferedReader reader = null;    StringBuffer resultBuffer = new StringBuffer();    String tempLine = null;    try {        localURL = new URL(urlStr);        URLConnection connection;        connection = localURL.openConnection();        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;        httpURLConnection.setDoOutput(true);        httpURLConnection.setRequestMethod("POST");        httpURLConnection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING);        httpURLConnection.setRequestProperty("Content-Type", "text/xml");        outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8");        outputStreamWriter.write(strInfo);        outputStreamWriter.flush();        outputStreamWriter.close();        //接收响应流        inputStream = httpURLConnection.getInputStream();        inputStreamReader = new InputStreamReader(inputStream);        reader = new BufferedReader(inputStreamReader);        while ((tempLine = reader.readLine()) != null) {            resultBuffer.append(tempLine);        }    } catch (IOException e) {        e.printStackTrace();    } catch (Exception e) {        e.printStackTrace();    } finally {        try {            if (outputStreamWriter != null) {                outputStreamWriter.close();            }            if (outputStream != null) {                outputStream.close();            }            if (reader != null) {                reader.close();            }            if (inputStreamReader != null) {                inputStreamReader.close();            }            if (inputStream != null) {                inputStream.close();            }        } catch (IOException e) {            e.printStackTrace();        } }      return resultBuffer.toString();

}


public static String post(String urlStr, String strInfo) {    String reStr="";    try {                URL url = new URL(urlStr);                URLConnection con =  url.openConnection();                con.setDoOutput(true);                con.setRequestProperty("Pragma:", "no-cache");                con.setRequestProperty("Cache-Control", "no-cache");                con.setRequestProperty("Content-Type", "text/xml");                OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());                out.write(new String(strInfo.getBytes("ISO-8859-1"),"UTF-8"));                out.flush();                out.close();                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));                String line = "";                for (line = br.readLine(); line != null; line = br.readLine()) {                    reStr += line;                }    } catch (MalformedURLException e) {         e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    return reStr;}

public static String post(String urlStr, String data){    String result = null;    //创建默认的httpclient实例     CloseableHttpClient client = HttpClients.createDefault();    //CloseableHttpClient client = new DefaultHttpClient();    StringEntity entity = new StringEntity(data, "UTF-8");    HttpPost post = new HttpPost(urlStr);    post.setEntity(entity);    try{        CloseableHttpResponse  response = client.execute(post);        result = EntityUtils.toString(response.getEntity());        System.out.println(result.toString());        response.close();    } catch (ClientProtocolException e1) {        e1.printStackTrace();    } catch (IOException e1) {        e1.printStackTrace();    } catch (Exception e) {        e.printStackTrace();    }    return result.toString();

}


public static String post(String urlStr, String data)throws ClientProtocolException, IOException{            String result = null;        //创建默认的httpclient实例         CloseableHttpClient client = HttpClients.createDefault();        StringEntity entity = new StringEntity(data, "UTF-8");        HttpPost post = new HttpPost(urlStr);        post.setEntity(entity);        CloseableHttpResponse response = client.execute(post);        try{            result = EntityUtils.toString(response.getEntity());            System.out.println(result.toString());        } catch (Exception e) {            e.printStackTrace();        }        finally {            response.close();        }        return result.toString();     }

get

public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {      JSONObject jsonObject = null;      StringBuffer buffer = new StringBuffer();      try {          URL url = new URL(requestUrl);          HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();          //httpUrlConn.setSSLSocketFactory(ssf);          httpUrlConn.setDoOutput(true);          httpUrlConn.setDoInput(true);          httpUrlConn.setUseCaches(false);          // 设置请求方式(GET/POST)          httpUrlConn.setRequestMethod(requestMethod);          if ("GET".equalsIgnoreCase(requestMethod))              httpUrlConn.connect();          // 当有数据需要提交时          if (null != outputStr) {              OutputStream outputStream = httpUrlConn.getOutputStream();              // 注意编码格式,防止中文乱码              outputStream.write(outputStr.getBytes("UTF-8"));              outputStream.close();          }          // 将返回的输入流转换成字符串          InputStream inputStream = httpUrlConn.getInputStream();          InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");          BufferedReader bufferedReader = new BufferedReader(inputStreamReader);          String str = null;          while ((str = bufferedReader.readLine()) != null) {              buffer.append(str);          }          bufferedReader.close();          inputStreamReader.close();          // 释放资源          inputStream.close();          inputStream = null;          httpUrlConn.disconnect();          jsonObject = JSONObject.fromObject(buffer.toString());      } catch (ConnectException ce) {          log.error("Weixin server connection timed out.");      } catch (Exception e) {          log.error("https request error:{}", e);      }      return jsonObject;  }

public static String get(String requestUrl) {      StringBuffer buffer = new StringBuffer();      try {          URL url = new URL(requestUrl);          HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();          httpUrlConn.setDoOutput(false);          httpUrlConn.setDoInput(true);          httpUrlConn.setUseCaches(false);          httpUrlConn.setRequestMethod("GET");          httpUrlConn.connect();          // 将返回的输入流转换成字符串          InputStream inputStream = httpUrlConn.getInputStream();          //InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");          InputStreamReader inputStreamReader = new InputStreamReader(inputStream);          BufferedReader bufferedReader = new BufferedReader(inputStreamReader);          String str = null;          while ((str = bufferedReader.readLine()) != null) {              buffer.append(str);          }          bufferedReader.close();          inputStreamReader.close();          // 释放资源          inputStream.close();          inputStream = null;          httpUrlConn.disconnect();      } catch (Exception e) {      }      return buffer.toString();  }

/**            * @Title: getUrl            * @Description: 发起httpGET请求            * @param url         * @return String             */        public static String getUrl(String url){        String result = null;        //创建默认的httpclient实例        CloseableHttpClient client = HttpClients.createDefault();        //根据地址获取请求        HttpGet get = new HttpGet(url);        //通过请求对象获取响应对象        try {            CloseableHttpResponse response=client.execute(get);            // 判断网络连接状态码是否正常(0--200都数正常)            try{            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                System.out.println("gqjcHttpUtil getUrl()方法 网络连接状态码正常");                //然而返回的实体内并没有,加这个会报空异常也是没办法                //System.out.println("获取数据编码方式为:"+response.getEntity().getContentEncoding().toString());                //要设置编码格式否则中文名有乱码                result= EntityUtils.toString(response.getEntity(), "utf-8");                System.out.println("gqjcHttpUtil result:"+result);                return result;                }             }finally {                response.close();            }        }

转载于:https://blog.51cto.com/liujin/2317382

你可能感兴趣的文章
nginx location配置详细解释
查看>>
matlab练习程序(感知哈希对比图片)
查看>>
命令模式(C++)
查看>>
ORM
查看>>
计算机网络:网际层
查看>>
python-ConfigParser模块【读写配置文件】
查看>>
Maven 的这 7 个问题你思考过没有?
查看>>
汇编浮点运算指令集
查看>>
闭包里面的函数调用时发生了什么
查看>>
wireshark使用方法总结
查看>>
9-27-函数
查看>>
yaf插件类的使用
查看>>
SSD内部的IO抖动因素
查看>>
Skype for Business Server 2015-04-前端服务器-4-准备Active Directory
查看>>
PHP流程控制的替代语法
查看>>
完全解析H3C路由器动态NAT配置步骤
查看>>
天涯的运维之路
查看>>
运维人员低学历者要不要补学历?何时补合适?
查看>>
【原创】日志表设计一例分析
查看>>
nmcli网卡绑定与teaming配置
查看>>