<div> 

package wzh.Http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
}

</div>

调用方法:

public static void main(String[] args) {
        //发送 GET 请求
        String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
        System.out.println(s);
        
        //发送 POST 请求
        String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
        System.out.println(sr);
    }

java 发送http 的get|post 请求的更多相关文章

  1. java发送http的get/post请求(一)

    HTTP请求类 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; ...

  2. java 发送 http post 和 get 请求(利用unirest)

    调用服务器端的接口在前端调用,但是我们也会经常遇到在服务器后端调用接口的情况,网上的例子大部分都是用 jdk 原生的 URL realUrl = new URL(url); URLConnection ...

  3. JAVA发送xml格式的接口请求

    /** * * @param urlStr 接口地址 * @param xmlInfo xml格式参数数据 * @return */ public static String sendMsgXml(S ...

  4. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  5. JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求

    JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求 哇,一看标题怎么这么长啊,其实意思很简单,哥讨厌用HTTP Client做POST与GET提交 觉得那个毕竟是别人写 ...

  6. 编写爬虫(spider)的预备知识:用java发送HTTP请求

    使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...

  7. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  8. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  9. 使用Java发送Http请求的内容

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容.这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过. 学习了J ...

随机推荐

  1. 48、ViewFlow ---- 滑动广告页

    <!-- main.xml --> <?xml version="1.0" encoding="utf-8"?> <LinearL ...

  2. Mybatis Insert 返回主键ID

    <insert id="insert" useGeneratedKeys="true" keyProperty="u_Id" para ...

  3. 对django模型中的objects的理解

    object是模型属性,用于模型对象和数据库交互. object=Manager()是管理器类型的对象,是model和数据库进行查询的接口 可以自定义管理对象 books=models.Manager ...

  4. 64位matlab mex64位编译器解决方案

    安装libsvm的时候用到了mex -setup,有的会报 Could not find the 64-bit compiler. This may indicate that the "X ...

  5. Server Objects Extension(SOE)开发(三)

    前言 SOE出现之前,一些复杂.耗时的gis操作,通常都是使用gp服务实现的.前面将gp服务和soe进行了对比分析,为了测试两种的效率,曾经做了个demo,使用soe和gp同时执行相同的业务逻辑,记录 ...

  6. AGS Server 10.1 切图工具

    在AGS Sever中很重要的功能就是地图缓存的制作,安装AGS Sever会在catalog中增加相关的工具箱,利用这些工具可以制作.删除.更新切片 一.Convert map server cac ...

  7. badboy脚本参数化和检查点

    一.badboy脚本参数化 文本参数化 方式一:直接在Variablesl ist添加参数化变量和值,然后在Script里面找到对应需要参数化的内容-属性,进行替换,参数化名需要用${XX}引用: 方 ...

  8. Model的save方法的使用

    在使用类方法创建对象的时候发生save()总提示缺少self参数的错误: class BookInfo(models.Model): #创建书本信息类,继承models.Model booktitle ...

  9. 前端框架之jQuery(二)----轮播图,放大镜

    事件 页面载入   ready(fn)  //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数.   $(document).ready(function(){}) -----------> ...

  10. centos系统时间相差8个小时解决方案

    查看当前系统时间 [root@centos64 ~]# date 查看硬件时间 [root@centos64 ~]# hwclock --show 同步时间可以用:ntpdate us.pool.nt ...