Ubuntu 14.04 Web 程序开发3Http Post & Get例子

实现「Http Post & Get例子」也是为了进一步熟悉Web开发,在之前的基础上做学习并测试。

曾经以为纯界面开发语言JavaScript可以实现Get Post和其它服务器进行通信,被指点需要结合后台PHP或者Java才可以之后有了方向。使用纯Java程序实现一个POST和GET之后,再结合之前的jsp的DEMO在jsp中实现。

首先查到一个JAVA版本的GET和POST例子:

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1","12345"));
params.add(new BasicNameValuePair("param-2","Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    InputStream instream = entity.getContent();
    try {
        // do something useful
    } finally {
        instream.close();
    }
}

来自:http://stackoverflow.com/a/3325065/2193455

将其放置到新建立的JavaPro工程中,导入需要的包后完整代码是:

// HelloWorld.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HelloWorld{

  // 程序的入口
  public static void main(String args[]) throws UnsupportedOperationException,IOException{
    // 向控制台输出信息
    System.out.println("欢迎java01班的同学");

    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://ip.taobao.com/service/getIpInfo.php");

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("ip","63.223.108.42"));
    httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
            System.out.print(convertStreamToString(instream));
        } finally {
            instream.close();
        }
    }
  }

  public static String convertStreamToString(InputStream is) {      
      /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */     
       BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
       StringBuilder sb = new StringBuilder();      

       String line = null;      
      try {      
          while ((line = reader.readLine()) != null) {      
               sb.append(line + "\n");      
           }      
       } catch (IOException e) {      
           e.printStackTrace();      
       } finally {      
          try {      
               is.close();      
           } catch (IOException e) {      
               e.printStackTrace();      
           }      
       }      

      return sb.toString();      
   }
}

需要导入Apache Http包才行,我使用的是httpcomponents-client-4.5-bin.tar.gz

Java版本的Http Post & Get例子运行完毕后如下成功:

接着就是将Java代码想办法写入Jsp:
1. 导入所需包

<%@page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="org.apache.http.message.*,org.apache.http.client.entity.*,org.apache.http.client.methods.*,java.io.*,java.util.*,org.apache.http.*,org.apache.http.client.*" %>

来源:在jsp中导入类和声明方法

  1. 按照要求贴入代码
<%
    java.util.Date d = new java.util.Date();
    String json = "";
    org.apache.http.client.HttpClient httpclient = org.apache.http.impl.client.HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://ip.taobao.com/service/getIpInfo.php");

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("ip","63.223.108.42"));
    httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

    HttpResponse resp = httpclient.execute(httppost);
    HttpEntity entity = resp.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
            json = convertStreamToString(instream);
            System.out.print(json);
        } finally {
            instream.close();
        }
    }
    %>
    <%!
      public static String convertStreamToString(InputStream is) {      
          /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */     
           BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
           StringBuilder sb = new StringBuilder();      

           String line = null;      
          try {      
              while ((line = reader.readLine()) != null) {      
                   sb.append(line + "\n");      
               }      
           } catch (IOException e) {      
               e.printStackTrace();      
           } finally {      
              try {      
                   is.close();      
               } catch (IOException e) {      
                   e.printStackTrace();      
               }      
           }      

          return sb.toString();      
       }
    %>

来源:找不到了,就是强调方法需要被<!%>包围。

完整的代码如下:

<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="org.apache.http.message.*,org.apache.http.client.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Title</title>
</head>
<body>
    <% java.util.Date d = new java.util.Date(); String json = ""; org.apache.http.client.HttpClient httpclient = org.apache.http.impl.client.HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://ip.taobao.com/service/getIpInfo.php"); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("ip","63.223.108.42")); httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); HttpResponse resp = httpclient.execute(httppost); HttpEntity entity = resp.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful json = convertStreamToString(instream); System.out.print(json); } finally { instream.close(); } } %>
    <%! public static String convertStreamToString(InputStream is) { /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder  * and returned as String. */ BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } %>
    <h1>
        Today's date is
        <%=d.toString()%>
        and this jsp page worked!
        Json is <%=json%>.
    </h1>
</body>
</html>

(代码后需要再加一行文字是为啥,这一行没有任何作用,只为了Markdown格式更好看)
3. 需要将Apache Http的Jar包复制到HelloWeb目录下,如下图所示:

4. 运行效果,Json语句顺利拿到,本此练习结束。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读2.3k次,点赞4次,收藏22次。最近安装了CARLA预编译版,总体过程感觉还是挺简单的,但是由于在网上找的参考资料并没有和自己遇到的情况完全一样的,所以把自己的安装过程记录下来,方便和自己一样的后来人进行安装,同时也自己作个记录留作备忘。其实预编译版的CARLA本身几乎不用什么命令行进行安装,主要步骤只有解压缩和拷贝文件,和极少的命令行安装操作。但是相关依赖以及其它的CARLA所使用的一些工具需要一起安装好,下面一起来看看安装步骤吧。_ubuntu22.04安装carla
文章浏览阅读6.3k次,点赞5次,收藏15次。在清华镜像中下载Ubuntu 20 安装包_ubuntu20下载
文章浏览阅读5k次。linux环境, python3.7.问题描述: 安装rally, pip3 install -r requirements.txt 时提示如下: 说明openssl 已安装。解决:1. pip3 install --upgrade pip , 结果输出如下 ..._error: command '/usr/bin/gcc' failed with exit code 1
文章浏览阅读1.1k次。自己刚踩坑装好的W11 WSL2 miniconda_wsl2 cuda
文章浏览阅读4.2k次,点赞4次,收藏17次。要安装这个 standalone的,会有一点区别(不识别 下面的 -localhost no)上面的命令会在~/.vnc/目录下生成一个 passwd文件。具体端口号,可以查看vncserver -list返回结果中的RFB PROT。作用是vncserver启动的时候运行这些命令,把桌面程序启动起来。如果希望用某个用户比如 demo登录,就用su切换到这个用户。桌面版默认就已安装,服务器版需要手动安装,并启动。关闭某个会话可以用下面的命令。远程地址输入ip:port。查看全部的vnc会话。_ubuntu vncserver
文章浏览阅读894次,点赞51次,收藏31次。在安卓使用vscode主要是连接一个远程的code-server服务,code-server服务安装在什么系统,调用的就是什么系统的环境,如这里使用ubuntu进行安装code-server,那使用的就是ubuntu环境,如需要go,python,java开发,需要在Ubuntu安装相关环境,创建的文件夹和项目也是在Ubuntu里面.这种方式其实在访问vscode的时候利于可以随时随地进行连接使用,且不受设备影响。
安装Ubuntu上超好用的终端Terminator。通过添加软件源、更新源、安装Terminator等步骤完成。
文章浏览阅读1.1k次,点赞83次,收藏74次。不要嫌弃Ubuntu的单调的终端界面啦,快来试试这些有意思的命令_ubuntu系统有趣的玩法
文章浏览阅读2.5k次。在ubuntu系统中,swap空间就是虚拟内存,所以考虑在磁盘空间富余的目录下设置虚拟内存swap文件,用来缓解内存不足的问题。通过上面的信息可以看到,/dev/vda2 目录下还剩余45G,那么就可以把swap文件生成在/dev/vda2目录下。在系统监控中发现,当数据库服务程序启动后,占用了大量内存空间,导致系统的剩余的内存往往只有几十MB。# bs 为块的大小,count 创建多少个块。# 执行命令后,删除创建的swap目录即可。#把生成的文件转换成 Swap 文件。2、创建一个swap文件。_ubuntu20修改swap大小
文章浏览阅读2.9k次,点赞2次,收藏10次。记录RV1126的SDK编译错误,以及解决处理_command exited with non-zero status 1
文章浏览阅读1.1w次,点赞22次,收藏101次。【记录】ubuntu20.04安装nvidia显卡驱动_ubuntu20.04安装nvidia显卡驱动
文章浏览阅读727次,点赞6次,收藏27次。在嵌入式Linux开发过程中,可能遇到uboot无法通过nfs服务从Ubuntu下载系统镜像(TTTTTT)的问题。如果你使用的是较新版本的Ubuntu,那么其**默认内核将不支持nfs2**!而**uboot仅支持到nfs2**,因此我们需要修改系统内核以及nfs配置文件,开启nfs2服务。**此问题非常棘手**,因为问题出现的时间太近,并且使用的人少。由于是2023年后才出现的问题,**chatgpt也无法解答**!本文参考网络上多篇博客资料,是解决此问题的最新办法。
ubuntu系统下安装软件的方法有多种,包括使用apt工具、deb软件包安装、源码编译安装以及通过软件中心安装。还有一种以 .run 后缀的软件包也可以在ubuntu系统下安装。具体的安装方法可以通过百度搜索来获取。
文章浏览阅读814次。本篇目的:Xubuntu如何安装pkg-configpkg-config是一个计算机软件包,用于帮助开发人员查找、定位和使用依赖库。它通常用于构建软件时,开发人员需要指定程序所依赖的外部库的位置和版本信息。使用pkg-config,开发人员可以很容易地查找、检索和导出这些依赖库的信息,从而简化了软件的构建过程。_ubuntu中怎么下载pkg-config
文章浏览阅读2k次。ubuntu创建共享文件夹_ubuntu20.04共享文件夹
文章浏览阅读2.9k次,点赞74次,收藏73次。对于有长期远程桌面需求的用户,建议将cpolar套餐升级到专业套餐,支持配置固定的公网TCP端口,且带宽也会相应的增大,支持更高效便捷的远程桌面连接Ubuntu系统。【cpolar内网穿透支持http/https/tcp协议,支持永久免费使用,不限制流量,无需公网IP,也不用进入路由器设置,操作简单。隧道创建成功后,点击左侧仪表盘的状态——在线隧道列表,查看xrdp隧道的所生成的公网TCP端口地址,复制下来。,使用cpolar内网穿透映射3389端口,生成公网TCP端口地址,实现在公网环境下,_ubuntu 局域网桌面
文章浏览阅读3.2k次。而在linux的ubuntu版本中,又多出两类用户:安装ubuntu系统的源用户xxx,其与root具有相同权限,仅在执行命令时,前面加sudo。在ubuntu中,用命令deluser username可以直接删除用户账号及家目录,而用centos7中的命令userdel -r username才能达到同样目的。在ubuntu中,没有moduser命令,centos7中的usermod修改用户信息的命令,同样可以用在ubuntu中。在系统中,创建新的用户或称为账号,一般需要多步操作。_ubuntu创建一个新用户
文章浏览阅读1.6w次,点赞4次,收藏23次。系统的许多日志文件都存储在 /var/log 目录中。你可以使用 ls /var/log 命令来列出可用的日志文件。/var/log/Xorg.0.log:包含 X 服务器的日志信息(图形界面)。打开DASH,搜索日志或者log,打开app,这个是/var/log的界面版。这将显示系统日志的末尾,并提供有关系统崩溃和错误的信息。/var/log/kern.log:包含内核日志信息。/var/log/dmesg:包含开机时的日志信息。/var/log/syslog:包含系统日志信息。_ubuntu查看系统日志
文章浏览阅读857次。首先将source.list复制为source.list.bak备份,然后将source.list内容改为需要的镜像源列表即可。Ubuntu采用apt作为软件安装工具,其镜像源列表记录在/etc/apt/source.list文件中。本节均为 Ubuntu 20.04 的镜像源列表。若为其他版本,将所有focal更改为其他版本代号即可。_apt 国内源