Java HttpURLConnection使用方法詳解
更新時間:2017年11月08日 08:55:27 作者:taz372436
這篇文章主要為大家詳細介紹了Java HttpURLConnection使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Java HttpURLConnection使用,供大家參考,具體內(nèi)容如下
包括使用HttpURLConnection執(zhí)行g(shù)et/post請求
package com.cn.testproject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpConnectionUrlDemo { public static void main(String[] args) throws Exception { //get(); post(); } public static void get() throws Exception { String path = "http://www.baidu.com"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); InputStream inStream = conn.getInputStream(); byte[] data = toByteArray(inStream); String result = new String(data, "UTF-8"); System.out.println(result); } public static void post() throws Exception { String encoding = "UTF-8"; //post的form參數(shù)(json兼職對) String params = "[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]"; String path = "http://www.baidu.com"; byte[] data = params.getBytes(encoding); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-javascript; charset=" + encoding); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setConnectTimeout(5 * 1000); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); System.out.println(conn.getResponseCode()); // 響應(yīng)代碼 200表示成功 if (conn.getResponseCode() == 200) { InputStream inStream = conn.getInputStream(); String result = new String(toByteArray(inStream), "UTF-8"); System.out.println(result); // 響應(yīng)代碼 200表示成功 } } private static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } }
GitHub:https://github.com/taz372436
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring AOP里的靜態(tài)代理和動態(tài)代理用法詳解
這篇文章主要介紹了 Spring AOP里的靜態(tài)代理和動態(tài)代理用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2020-07-07SpringBoot整合mybatis-plus進階詳細教程
本文主要對mybatis-plus的條件構(gòu)造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動填充等知識點進行講解,需要的朋友參考下吧2021-09-09Spring Boot 2.x中Actuator的一些知識點
這篇文章主要給大家介紹了關(guān)于Spring Boot 2.x中Actuator的一些知識點,文中通過示例代碼介紹的非常詳細,對大家學(xué)習或者使用Spring Boot 2.x具有一定的參考學(xué)習價值,需要的朋友們下面來一起學(xué)習學(xué)習吧2019-09-09oracle數(shù)據(jù)庫導(dǎo)入TXT文件方法介紹
這篇文章主要介紹了oracle數(shù)據(jù)庫導(dǎo)入TXT文件方法介紹,文中向大家展示了具體代碼示例,需要的朋友可以參考下。2017-09-09