zoukankan      html  css  js  c++  java
  • Http协议:客户端提交数据给服务端和从服务端获得数据,像WebView也是向百度的服务端发出一条Http请求,服务端返回HTML页面,客户端(浏览器)解析后展示出页面

    提交数据和获得数据的方式有很多,这里介绍一种,使用HttpURLConnection来向服务器提交数据或者获得数据。

    获得数据:

    //传入网址,获得请求网页数据(XML文件数据或JSON文件数据)
    public static String sendHttpRequest(String address) {
    HttpURLConnection connection=null;
    try {
    URL url=new URL(address);
    connection=(HttpURLConnection)url.openConnection();
    //设置请求方式:GET为从服务器获得数据,POST为提交数据
    connection.setRequestMethod("GET");
    //设置连接最长超时时间(单位毫秒)
    connection.setConnectTimeout(8000);
    //设置读取最长超时时间(单位毫秒)
    connection.setReadTimeout(8000);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    //获取到的数据输入流(InputStream为抽象类)
    InputStream in=connection.getInputStream();
    //对输入流进行读取
    BufferedReader reader=new BufferedReader(new InputStreamReader(in));
    StringBuffer response = new StringBuffer();
    String line;
    while((line=reader.readLine()) != null) {
    response.append(line);
    }
    return response.toString();

    } catch (Exception e) {
    e.printStackTrace();
    return e.getMessage();
    }finally {
    if(connection!=null) {
    connection.disconnect();
    }
    }

    提交数据: 

    public static void submit(String address) {
    HttpURLConnection connection=null;
    try {
    //设置为提交模式
    connection.setRequestMethod("POST");
    DataOutputStream out=new DataOutputStream(connection.getOutputStream());
    out.writeBytes("username=admin&password=123456");//数据与数据之间用&分割
    }catch (Exception e) {
    e.printStackTrace(http://www.amjmh.com/v/);
    }finally {
    if(connection!=null) {
    connection.disconnect();
    }
    }
    }

  • 相关阅读:
    【JAVA SE基础篇】28.面向对象三大特征之多态
    【JAVA SE基础篇】27.面向对象三大特征之封装
    【JAVA SE基础篇】26.toString()方法和equlas()方法
    【JAVA SE基础篇】25.面向对象三大特征之继承
    【JAVA SE基础篇】24.包的机制和import详解
    ssh框架文件上传下载
    java格式化时间格式
    表单提交后打印后台传过来的数据
    使用ajaxfileupload.js实现文件上传
    JSTL跳出<c:forEach>循环
  • 原文地址:https://www.cnblogs.com/ly570/p/11379420.html
Copyright © 2011-2022 走看看