zoukankan      html  css  js  c++  java
  • Java 发送Get和Post请求

      1 package com.htpt.superviseServices.dm.util;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.IOException;
      5 import java.io.InputStreamReader;
      6 import java.io.PrintWriter;
      7 import java.net.URL;
      8 import java.net.URLConnection;
      9 import java.util.List;
     10 import java.util.Map;
     11 
     12 import net.sf.json.JSONArray;
     13 
     14 public class HttpRequest {
     15     /**
     16      * 向指定URL发送GET方法的请求
     17      * 
     18      * @param url
     19      *            发送请求的URL
     20      * @param param
     21      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     22      * @return URL 所代表远程资源的响应结果
     23      */
     24     public static Boolean sendGet(String lon, String lat) {
     25         String result = "";
     26         BufferedReader in = null;
     27         String city = "";
     28         try {
     29             String urlNameString = "http://api.map.baidu.com/geocoder/v2/?ak=56E117E2740978010ece5593e91b00e3&output=json&coordtype=wgs84ll&location="+lat+","+lon;
     30             URL realUrl = new URL(urlNameString);
     31             // 打开和URL之间的连接
     32             URLConnection connection = realUrl.openConnection();
     33             // 设置通用的请求属性
     34             connection.setRequestProperty("accept", "*/*");
     35             connection.setRequestProperty("connection", "Keep-Alive");
     36             connection.setRequestProperty("user-agent",
     37                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
     38             // 建立实际的连接
     39             connection.connect();
     40             // 获取所有响应头字段
     41             Map<String, List<String>> map = connection.getHeaderFields();
     42             // 遍历所有的响应头字段
     43             for (String key : map.keySet()) {
     44                 System.out.println(key + "--->" + map.get(key));
     45             }
     46             // 定义 BufferedReader输入流来读取URL的响应
     47             in = new BufferedReader(new InputStreamReader(
     48                     connection.getInputStream()));
     49             String line;
     50             while ((line = in.readLine()) != null) {
     51                 result += line;
     52             }
     53             JSONArray data = JSONArray.fromObject("["+result+"]");
     54             Map dataMap = (Map) data.get(0);
     55             Map dataResult = (Map)dataMap.get("result");
     56             Map addressComponent = (Map)dataResult.get("addressComponent");
     57             city = (String) addressComponent.get("city");      
     58         } catch (Exception e) {
     59             System.out.println("发送GET请求出现异常!" + e);
     60             e.printStackTrace();
     61         }
     62         // 使用finally块来关闭输入流
     63         finally {
     64             try {
     65                 if (in != null) {
     66                     in.close();
     67                 }
     68             } catch (Exception e2) {
     69                 e2.printStackTrace();
     70             }
     71         }
     72         System.out.println(city);
     73         return "长沙市".equals(city);
     74     }
     75 
     76     /**
     77      * 向指定 URL 发送POST方法的请求
     78      * 
     79      * @param url
     80      *            发送请求的 URL
     81      * @param param
     82      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     83      * @return 所代表远程资源的响应结果
     84      */
     85     public static String sendPost(String url, String param) {
     86         PrintWriter out = null;
     87         BufferedReader in = null;
     88         String result = "";
     89         try {
     90             URL realUrl = new URL(url);
     91             // 打开和URL之间的连接
     92             URLConnection conn = realUrl.openConnection();
     93             // 设置通用的请求属性
     94             conn.setRequestProperty("accept", "*/*");
     95             conn.setRequestProperty("connection", "Keep-Alive");
     96             conn.setRequestProperty("user-agent",
     97                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
     98             // 发送POST请求必须设置如下两行
     99             conn.setDoOutput(true);
    100             conn.setDoInput(true);
    101             // 获取URLConnection对象对应的输出流
    102             out = new PrintWriter(conn.getOutputStream());
    103             // 发送请求参数
    104             out.print(param);
    105             // flush输出流的缓冲
    106             out.flush();
    107             // 定义BufferedReader输入流来读取URL的响应
    108             in = new BufferedReader(
    109                     new InputStreamReader(conn.getInputStream()));
    110             String line;
    111             while ((line = in.readLine()) != null) {
    112                 result += line;
    113             }
    114         } catch (Exception e) {
    115             System.out.println("发送 POST 请求出现异常!"+e);
    116             e.printStackTrace();
    117         }
    118         //使用finally块来关闭输出流、输入流
    119         finally{
    120             try{
    121                 if(out!=null){
    122                     out.close();
    123                 }
    124                 if(in!=null){
    125                     in.close();
    126                 }
    127             }
    128             catch(IOException ex){
    129                 ex.printStackTrace();
    130             }
    131         }
    132         return result;
    133     }
    134 }
  • 相关阅读:
    Asp.net2.0页面执行顺序 朱燚:
    通过对比学Python(2):集合对象 朱燚:
    通过比较学python(3):字典类,字符串 朱燚:
    [模版项目]怎样用企业服务实现跨进程缓存 朱燚:
    [轻松一下]世界上至少有10種東西是你不知道的 朱燚:
    评:我从编程中悟出八个字(不算原创,不过希望让大家能看看) 朱燚:
    从追MM谈Java的23种设计模式 朱燚:
    学习笔记_Redis 数据类型02
    MongoDB.Driver 中通过管道(Aggregate)实现分组功能查询出符合条件的数据
    MongoDB.Driver 中实现参数动态查询
  • 原文地址:https://www.cnblogs.com/zouqin/p/5413282.html
Copyright © 2011-2022 走看看