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

前端之家收集整理的这篇文章主要介绍了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.*" %>

<!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语句顺利拿到,本此练习结束。

原文链接:https://www.f2er.com/ubuntu/355900.html

猜你在找的Ubuntu相关文章