Ubuntu 14.04 Web 程序开发(3)Http 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.entity.*, org.apache.http.client.methods.*, java.io.*, java.util.*, org.apache.http.*, 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语句顺利拿到,本此练习结束。
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁保康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值