搜尋
首頁Javajava教程java:http請求(程式碼詳解)

java原生API

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;
    }    
    /**
     * @param args
     */
    public static void main(String[] args) {        // TODO Auto-generated method stub
          //发送 GET 请求//        String s=HttpRequest.sendGet("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo", "mobileCode=13069208531&userID=");//        System.out.println(s);

        //发送 POST 请求
        String sr=HttpRequest.sendPost("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo", "mobileCode=13069208531&userID=");
        System.out.println(sr);
    }

}

httpclient  需要 jar套件:
java:http請求(程式碼詳解)

public class HTTPUtils {
     private final static Logger logger = Logger.getLogger(HTTPUtils.class);     private final static String OPERATER_NAME = "【HTTP操作】";     private final static int SUCCESS = 200;     private final static String UTF8 = "UTF-8";     private HttpClient client;     private final String respondTypeXML = "application/x-www-form-urlencoded";     private final String respondTypeJSON = "application/json;charse=UTF-8";     private static HTTPUtils instance = new HTTPUtils();     private HTTPUtils() {
         HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
         HttpConnectionManagerParams params = httpConnectionManager.getParams();
         params.setConnectionTimeout(5000);
         params.setSoTimeout(20000);
         params.setDefaultMaxConnectionsPerHost(1000);
         params.setMaxTotalConnections(1000);
         client = new HttpClient(httpConnectionManager);
         client.getParams().setContentCharset(UTF8);
         client.getParams().setHttpElementCharset(UTF8);
         }     public static String get(URL url) {         return instance.doGet(url);
         }    private String doGet(URL url) {        long beginTime = System.currentTimeMillis();
        String respStr = "";
        HttpMethod method = null;        try {
            logger.info(OPERATER_NAME + "开始get通信,目标host:" + url);
            method = new GetMethod(url.toString());            // 中文转码
            method.getParams().setContentCharset(UTF8);            try {
                client.executeMethod(method);
            } catch (HttpException e) {

                logger.error(new StringBuffer("发送HTTP GET给\r\n").append(url)
                        .append("\r\nHTTP异常\r\n"), e);
            } catch (IOException e) {

                logger.error(new StringBuffer("发送HTTP GET给\r\n").append(url)
                        .append("\r\nIO异常\r\n"), e);
            }            if (method.getStatusCode() == SUCCESS) {
                respStr = method.getResponseBodyAsString();
            }
            logger.info(OPERATER_NAME + "通讯完成,返回码:" + method.getStatusCode());
            logger.info(OPERATER_NAME + "返回内容:"
                    + method.getResponseBodyAsString());
            logger.info(OPERATER_NAME + "结束..返回结果:" + respStr);
        } catch (Exception e) {
            logger.info(OPERATER_NAME, e);
        }finally{            if(method != null){
                method.releaseConnection();
            }
        }        long endTime = System.currentTimeMillis();
        logger.info(OPERATER_NAME + "共计耗时:" + (endTime - beginTime) + "ms");        return respStr;
    }    /**
     * POST请求
     */
    public static String post(URL url, String content) {        return instance.doPost(url, content);
    }    private String doPost(URL url, String content) {        long beginTime = System.currentTimeMillis();
        String respStr = "";
        PostMethod post = null;        try {
            logger.info(OPERATER_NAME + "开始post通信,目标host:" + url.toString());
            logger.info("通信内容:" + content);
            post = new PostMethod(url.toString());
            RequestEntity requestEntity = new StringRequestEntity(content,
                    respondTypeXML, UTF8);
            post.setRequestEntity(requestEntity);            // 设置格式
            post.getParams().setContentCharset(UTF8);

            client.executeMethod(post);            if (post.getStatusCode() == SUCCESS) {
                respStr = post.getResponseBodyAsString();
            }

            logger.info(OPERATER_NAME + "通讯完成,返回码:" + post.getStatusCode());
            logger.info(OPERATER_NAME + "返回内容:"
                    + post.getResponseBodyAsString());
            logger.info(OPERATER_NAME + "结束..返回结果:" + respStr);
            post.releaseConnection();

        } catch (Exception e) {
            logger.error(OPERATER_NAME, e);
        }finally{            if(post != null){
                post.releaseConnection();
            }
        }        long endTime = System.currentTimeMillis();
        logger.info(OPERATER_NAME + "共计耗时:" + (endTime - beginTime) + "ms");        return respStr;
    }    /**
     * @param args
     * @throws MalformedURLException
     */
    public static void main(String[] args) throws MalformedURLException {        // TODO Auto-generated method stub
        JSONObject json = new JSONObject();
        json.put("mobileCode", "13069208531");
        json.put("userID", "");
        URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");//      URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"//              + "/getMobileCodeInfo?mobileCode=13069208531&userID=");
            String resp = post(url, json.toString());        //String resp = get(url);
        System.out.println("resp:"+resp);
    }
}

httpclient:

public class HttpClientUtil {


    public static void get(String number) throws Exception{
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"
                + "/getMobileCodeInfo?mobileCode=" + number + "&userID=");        // 指定传输的格式为get请求格式
        get.setRequestHeader("Content-Type", "text/xml; charset=utf-8");        // 发送请求
        int code = client.executeMethod(get);
        System.out.println("Http:状态码为:" + code);

        String result = get.getResponseBodyAsString();
        System.out.println("返回的结果为:" + result);
    }    public static void post(String number) throws Exception {        //HttpClient:在java代码中模拟Http请求
        // 创建浏览器对象
        HttpClient client = new HttpClient();        // 填写数据,发送get或者post请求
        PostMethod post = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");        // 指定传输的格式为默认post格式
        post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");     
        // 传输参数
        post.setParameter("mobileCode", number);
        post.setParameter("userID", "");        // 发送请求
        int code = client.executeMethod(post);
        System.out.println("Http:状态码为:" + code);

        String result = post.getResponseBodyAsString();
        System.out.println("返回的结果为:" + result);
    }    /**
     * @Description soap post方式请求,但是传输的数据为xml格式,有利于数据的维护
     * @param number
     * @throws Exception
     */
    //它有两个版本soap1.1和soap1.2,jdk1.7及以上才可以使用soap1.2。
    public void soap(String number) throws Exception {        //HttpClient:在java代码中模拟Http请求
        // 创建浏览器对象
        HttpClient client = new HttpClient();        // 填写数据,发送get或者post请求
        PostMethod post = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");        // 指定传输的格式为xml格式
        post.setRequestHeader("Content-Type", "application/soap+xml;charset=utf-8");        // 传输xml,加载soap.txt
       InputStream in = HttpClientUtil.class.getClassLoader().getResourceAsStream("/soap.txt");//返回值是一个InputStream
        post.setRequestBody(in);        // 发送请求
        int code = client.executeMethod(post);
        System.out.println("Http:状态码为:" + code);

        String result = post.getResponseBodyAsString();        // 如果采用的是soap,则返回的数据也是基于xml的soap格式
        System.out.println("返回的结果为:" + result);
    }    //wsimport -s . -p com.hexy.ws http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL 
    public static void wsdl(){        // 获取一个ws服务
        MobileCodeWS ws = new MobileCodeWS();        // 获取具体的服务类型:get post soap1.1 soap1.2
        MobileCodeWSSoap wsSoap = ws.getMobileCodeWSSoap();
        String address = wsSoap.getMobileCodeInfo("18312345678", null);
        System.out.println("手机归属地信息为:" + address);
    }    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {        // TODO Auto-generated method stub
        post("18312345678");        //wsdl();
        //soap("18312345678");
    }

}

soap.txt

<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
      <mobileCode>13069208531</mobileCode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body></soap12:Envelope>

相關建議:

網路- Java 非同步http請求。

Java與Http協定的詳解

以上是java:http請求(程式碼詳解)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。