`
aloofqq
  • 浏览: 28627 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一个使用URL类响应邮件请求的实例源码

    博客分类:
  • Java
阅读更多
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
   This program demonstrates how to use the URLConnection class for a POST request. 
*/
public class PostTest
{  
   public static void main(String[] args)
   {  
      JFrame frame = new PostTestFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

class PostTestFrame extends JFrame
{  
   /**
      Makes a POST request and returns the server response.
      @param urlString the URL to post to
      @param nameValuePairs a map of name/value pairs to supply in the request.
      @return the server reply (either from the input stream or the error stream)
   */
   public static String doPost(String urlString, Map<String, String> nameValuePairs) 
      throws IOException
   {  
      URL url = new URL(urlString);
      URLConnection connection = url.openConnection();
      connection.setDoOutput(true);

      PrintWriter out = new PrintWriter(connection.getOutputStream());

      boolean first = true;
      for (Map.Entry<String, String> pair : nameValuePairs.entrySet())
      {  
         if (first) first = false; 
         else out.print('&'); 
         String name = pair.getKey();
         String value = pair.getValue();
         out.print(name);
         out.print('=');
         out.print(URLEncoder.encode(value, "UTF-8"));
      }

      out.close();

      Scanner in;
      StringBuilder response = new StringBuilder();
      try
      {  
         in = new Scanner(connection.getInputStream());
      }
      catch (IOException e)
      {  
         if (!(connection instanceof HttpURLConnection)) throw e;
         InputStream err
            = ((HttpURLConnection)connection).getErrorStream();
         if (err == null) throw e;
         in = new Scanner(err);
      }
      while (in.hasNextLine())
      {
         response.append(in.nextLine());
         response.append("\n");
      }

      in.close();
      return response.toString();
   }

   public PostTestFrame()
   {  
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      setTitle("PostTest");

      JPanel northPanel = new JPanel();
      add(northPanel, BorderLayout.NORTH);

      final JComboBox combo = new JComboBox();
      for (int i = 0; i < countries.length; i += 2)
      combo.addItem(countries[i]);
      northPanel.add(combo);

      final JTextArea result = new JTextArea();
      add(new JScrollPane(result));

      JButton getButton = new JButton("Get");
      northPanel.add(getButton);
      getButton.addActionListener(new
         ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {  
               new Thread(new 
                  Runnable()
                  {
                     public void run()
                     {   
                        final String SERVER_URL = "127.0.0.1";
                        result.setText("");
                        Map<String, String> post = new HashMap<String, String>();
                        post.put("tbl", "001");
                        post.put("cty", countries[2 * combo.getSelectedIndex() + 1]);
                        post.put("optyr", "latest checked");
                        try
                        {
                           result.setText(doPost(SERVER_URL, post));
                        }
                        catch (IOException e)
                        {
                           result.setText("" + e);
                        }
                     }
                  }).start();
            }            
         });   
   }

   private static String[] countries = {
      "Afghanistan", "AF", "Albania", "AL", "Algeria", "AG", "American Samoa", "AQ",
      "Andorra", "AN", "Angola", "AO", "Anguilla", "AV", "Antigua and Barbuda", "AC",
      "Argentina", "AR", "Armenia", "AM", "Aruba", "AA", "Australia", "AS", "Austria", "AU",
      "Azerbaijan", "AJ", "Bahamas, The", "BF", "Bahrain", "BA", "Bangladesh", "BG",
      "Barbados", "BB", "Belarus", "BO", "Belgium", "BE", "Belize", "BH", "Benin", "BN",
      "Bermuda", "BD", "Bhutan", "BT", "Bolivia", "BL", "Bosnia and Herzegovina", "BK",
      "Botswana", "BC", "Brazil", "BR", "Brunei", "BX", "Bulgaria", "BU", "Burkina Faso", "UV",
      "Burma", "BM", "Burundi", "BY", "Cambodia", "CB", "Cameroon", "CM", "Canada", "CA",
      "Cape Verde", "CV", "Cayman Islands", "CJ", "Central African Republic", "CT", "Chad", "CD",
      "Chile", "CI", "China", "CH", "Colombia", "CO", "Comoros", "CN", "Congo (Brazzaville", "CF",
      "Congo (Kinshasa)", "CG", "Cook Islands", "CW", "Costa Rica", "CS", "Cote d'Ivoire", "IV",
      "Croatia", "HR", "Cuba", "CU", "Cyprus", "CY", "Czech Republic", "EZ", "Denmark", "DA",
      "Djibouti", "DJ", "Dominica", "DO", "Dominican Republic", "DR", "East Timor", "TT",
      "Ecuador", "EC", "Egypt", "EG", "El Salvador", "ES", "Equatorial Guinea", "EK",
      "Eritrea", "ER", "Estonia", "EN", "Ethiopia", "ET", "Faroe Islands", "FO", "Fiji", "FJ",
      "Finland", "FI", "France", "FR", "French Guiana", "FG", "French Polynesia", "FP",
      "Gabon", "GB", "Gambia, The", "GA", "Gaza Strip", "GZ", "Georgia", "GG", "Germany", "GM",
      "Ghana", "GH", "Gibraltar", "GI", "Greece", "GR", "Greenland", "GL", "Grenada", "GJ",
      "Guadeloupe", "GP", "Guam", "GQ", "Guatemala", "GT", "Guernsey", "GK", "Guinea", "GV",
      "Guinea-Bissau", "PU", "Guyana", "GY", "Haiti", "HA", "Honduras", "HO", 
      "Hong Kong S.A.R", "HK", "Hungary", "HU", "Iceland", "IC", "India", "IN", "Indonesia", "ID",
      "Iran", "IR", "Iraq", "IZ", "Ireland", "EI", "Israel", "IS", "Italy", "IT", "Jamaica", "JM",
      "Japan", "JA", "Jersey", "JE", "Jordan", "JO", "Kazakhstan", "KZ", "Kenya", "KE",
      "Kiribati", "KR", "Korea, North", "KN", "Korea, South", "KS", "Kuwait", "KU", 
      "Kyrgyzstan", "KG", "Laos", "LA", "Latvia", "LG", "Lebanon", "LE", "Lesotho", "LT", 
      "Liberia", "LI", "Libya", "LY", "Liechtenstein", "LS", "Lithuania", "LH", "Luxembourg", "LU",
      "Macau S.A.R", "MC", "Macedonia, The Former Yugo. Rep. of", "MK", "Madagascar", "MA",
      "Malawi", "MI", "Malaysia", "MY", "Maldives", "MV", "Mali", "ML", "Malta", "MT",
      "Man, Isle of", "IM", "Marshall Islands", "RM", "Martinique", "MB", "Mauritania", "MR",
      "Mauritius", "MP", "Mayotte", "MF", "Mexico", "MX", "Micronesia, Federated States of", "FM",
      "Moldova", "MD", "Monaco", "MN", "Mongolia", "MG", "Montserrat", "MH", "Morocco", "MO",
      "Mozambique", "MZ", "Namibia", "WA", "Nauru", "NR", "Nepal", "NP", "Netherlands", "NL",
      "Netherlands Antilles", "NT", "New Caledonia", "NC", "New Zealand", "NZ", "Nicaragua", "NU",
      "Niger", "NG", "Nigeria", "NI", "Northern Mariana Islands", "CQ", "Norway", "NO",
      "Oman", "MU", "Pakistan", "PK", "Palau", "PS", "Panama", "PM", "Papua New Guinea", "PP",
      "Paraguay", "PA", "Peru", "PE", "Philippines", "RP", "Poland", "PL", "Portugal", "PO",
      "Puerto Rico", "RQ", "Qatar", "QA", "Reunion", "RE", "Romania", "RO", "Russia", "RS",
      "Rwanda", "RW", "Saint Helena", "SH", "Saint Kitts and Nevis", "SC", "Saint Lucia", "ST",
      "Saint Pierre and Miquelon", "SB", "Saint Vincent and the Grenadines", "VC", "Samoa", "WS",
      "San Marino", "SM", "Sao Tome and Principe", "TP", "Saudi Arabia", "SA", "Senegal", "SG",
      "Serbia and Montenegro", "YI", "Seychelles", "SE", "Sierra Leone", "SL", "Singapore", "SN",
      "Slovakia", "LO", "Slovenia", "SI", "Solomon Islands", "BP", "Somalia", "SO",
      "South Africa", "SF", "Spain", "SP", "Sri Lanka", "CE", "Sudan", "SU", "Suriname", "NS",
      "Swaziland", "WZ", "Sweden", "SW", "Switzerland", "SZ", "Syria", "SY", "Taiwan", "TW",
      "Tajikistan", "TI", "Tanzania", "TZ", "Thailand", "TH", "Togo", "TO", "Tonga", "TN",
      "Trinidad and Tobago", "TD", "Tunisia", "TS", "Turkey", "TU", "Turkmenistan", "TX",
      "Turks and Caicos Islands", "TK", "Tuvalu", "TV", "Uganda", "UG", "Ukraine", "UP",
      "United Arab Emirates", "TC", "United Kingdom", "UK", "United States", "US", "Uruguay", "UY",
      "Uzbekistan", "UZ", "Vanuatu", "NH", "Venezuela", "VE", "Vietnam", "VM", 
      "Virgin Islands", "VQ", "Virgin Islands, British", "VI", "Wallis and Futuna", "WF",
      "West Bank", "WE", "Western Sahara", "WI", "Yemen", "YM", "Zambia", "ZA", "Zimbabwe", "ZI"
   };

   public static final int DEFAULT_WIDTH = 400;
   public static final int DEFAULT_HEIGHT = 300;  
}



PostTest.properties文件
URL=http://www.census.gov/cgi-bin/ipc/idbsprd
tbl=001
cty=CH
optyr=latest checked
分享到:
评论

相关推荐

    Java抓取URL/Email实例源码

    本实例源码是关于如何使用Java进行URL和Email抓取的实践案例。 首先,我们需要理解基本的网页抓取原理。网页抓取通常通过HTTP或HTTPS协议与服务器交互,发送请求并接收响应。Java中的`java.net.URL`类可以帮助我们...

    BCB gsoap实例源码

    这会生成一系列的源文件,包括用于处理SOAP请求和响应的类以及数据结构。 3. **连接到服务**:在C++ Builder 6项目中,引入生成的源代码,并实例化gsoap的`soap`对象。通过这个对象,你可以设置服务的URL和其他连接...

    AjAX程序实例源码

    总结,这个" AjAX程序实例源码 "提供了一个完整的Ajax应用范例,涵盖了从客户端JavaScript的Ajax调用,到Java后端的处理流程。通过学习和分析这个实例,开发者能够深入理解Ajax技术,并具备实现在自己的项目中运用...

    django1.8官方实例程序源码

    通过学习和分析这些源码,你可以深入掌握如何构建一个基本的Django应用。 **一、Django项目结构** 在`mysite`这个压缩包中,我们首先会看到Django项目的标准结构: 1. `manage.py`: 这是一个命令行工具,用于执行...

    django入门博客实例源码

    **Django入门博客实例源码解析** Django是一款用Python编写的高级Web框架,它遵循“ Batteries Included ”的理念,提供了许多内置功能和强大的工具,让开发者能够快速地构建高质量的Web应用。在这个入门博客实例中...

    asp+jquery ajax实例源码,添加,删除,修改,分页

    jQuery 是一个流行的JavaScript库,它简化了DOM操作、事件处理、动画以及AJAX交互。AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个网页的情况下,能够更新部分网页的技术。在这个实例源码中,我们...

    Ajax网站开发典型实例JSP源码包

    Ajax(Asynchronous JavaScript ...这个源码包提供了一个实践平台,让你深入理解Ajax与JSP的结合,如何构建高性能、高交互性的Web应用。通过研究和学习每个文件,你可以提升你的Web开发技能,并将其应用到实际项目中。

    C# 普通下载 实例源码(网络操作)

    创建一个`FileStream`实例,指定文件路径和写入模式,然后将网络流中的数据写入文件流。 下面是一个简单的C#文件下载示例代码: ```csharp using System; using System.IO; using System.Net; public class ...

    express框架实例源码

    一个请求会依次通过这些函数,直到遇到返回响应或者结束请求。例如,可以使用`app.use()`添加全局中间件,或者在特定路由下使用`router.use()`。 3. **路由处理**:在`express02`、`express07`等文件中,可能会包含...

    ajax实例源码

    创建一个XMLHttpRequest对象,然后通过open()方法设置请求类型(GET或POST)、URL和是否异步,最后使用send()方法发送请求。 2. **事件处理**:在发送请求后,我们需要监听XMLHttpRequest对象的onreadystatechange...

    Qt5开发及实例源码

    Qt5是Qt库的一个主要版本,它在2012年发布,提供了许多新功能和改进,使得开发者能够更高效地构建跨平台的图形用户界面应用程序。Qt5的开发涵盖了C++语言,同时引入了QML(Qt Meta Language),这是一种声明性的语言...

    volley框架源码实例

    Volley是一个由Google开发的Android网络请求库,它旨在提供高效、快速的网络通信解决方案。在Android应用开发中,Volley被广泛用于处理HTTP请求,如GET、POST等,以及JSON数据的解析。这个"volley框架源码实例"包含...

    ajax经典入门实例源码

    **Ajax(Asynchronous JavaScript and ...总之,`ajax经典入门实例源码`提供了一个实践平台,通过实际操作加深对Ajax的理解。结合`readme.txt`的指导,你应该能逐步掌握Ajax的基本使用,为后续的Web开发打下坚实基础。

    Java中的SSL及HTTPS协议实例源码

    这个简单的示例展示了如何使用Java的`HttpsURLConnection`发起一个HTTPS请求,获取并打印服务器的响应。在实际应用中,可能还需要处理证书验证、自定义SSLContext等更复杂的场景。 总的来说,理解Java中的SSL和...

    基于Java的实例源码-一个支持servlet的web服务器.zip

    在Java中,Servlet是一个实现了Servlet接口的类,它接收并响应来自Web客户端的请求。Servlet API是Java Servlet规范的一部分,它定义了Servlet如何与Web服务器交互。在本实例中,我们可以期待看到以下几个关键组成...

    安卓Android源码——与php服务器交互实例源码.zip

    本实例源码着重展示了如何在Android应用中通过PHP服务器进行数据通信。下面将详细解释这一过程涉及的关键知识点。 1. **HTTP通信协议**:Android应用与服务器之间的交互通常基于HTTP或HTTPS协议。HTTP允许客户端...

    jquery+ajax+json+servlet实例源码

    这个实例源码主要展示了如何在Web开发中利用jQuery库进行AJAX异步请求,与后台Servlet进行数据交互,并通过JSON格式来序列化和反序列化数据。这些技术是现代Web应用中常见的组件,对于前端与后端通信至关重要。 ...

    Axis WebService 实例源码

    总结,"Axis WebService 实例源码"是一个很好的学习资源,它涵盖了从设置开发环境到实现、部署和测试Web服务的基本步骤。通过深入研究这个实例,开发者可以更好地理解和掌握基于Java的Web服务开发。

    Android studio中完整demo实例源码可运行

    【Android Studio 中的完整 Demo 实例源码可运行】 在 Android 开发中,Android Studio 是 Google 推出的官方集成开发环境(IDE),它为开发者提供了丰富的功能和工具,使得 Android 应用程序的开发更加高效。这个...

    PHP在线考试系统实例源码

    【PHP在线考试系统实例源码】是一个无需数据库且无后台管理功能的PHP应用程序,它提供了一个简单的平台,使用户能够进行在线的自我测试和学习。这个系统的核心目标是简化考试流程,让开发者或教育者可以快速搭建一个...

Global site tag (gtag.js) - Google Analytics