精华内容
下载资源
问答
  • 通过Java发送http请求

    2021-01-21 17:12:33
     下面为大家提供一个Java发送http请求的工具类 HttpRequest.java package org.javahttp.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java....
  • JAVA发送http get/post请求,调用http接口、方法

    万次阅读 多人点赞 2016-07-05 17:56:29
    三个例子 —JAVA发送http get/post请求,调用http接口、方法例1:使用 HttpClient (commons-httpclient-3.0.jar jar下载地址:http://download.csdn.net/download/capmiachael/9760550)import java.io....

    三个例子 —JAVA发送http get/post请求,调用http接口、方法

    例1:使用 HttpClient (commons-httpclient-3.0.jar
    jar下载地址:http://download.csdn.net/download/capmiachael/9760550

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.RequestEntity;
    
    public class HttpTool {
    
    	/**
    	 * 发送post请求
    	 * 
    	 * @author Michael -----CSDN: http://blog.csdn.net/capmiachael
    	 * @param params
    	 *            参数
    	 * @param requestUrl
    	 *            请求地址
    	 * @param authorization
    	 *            授权书
    	 * @return 返回结果
    	 * @throws IOException
    	 */
    	public static String sendPost(String params, String requestUrl,
    			String authorization) throws IOException {
    
    		byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
    		HttpClient httpClient = new HttpClient();// 客户端实例化
    		PostMethod postMethod = new PostMethod(requestUrl);
    		//设置请求头Authorization
    		postMethod.setRequestHeader("Authorization", "Basic " + authorization);
    		// 设置请求头  Content-Type
    		postMethod.setRequestHeader("Content-Type", "application/json");
    		InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
    				requestBytes.length);
    		RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
    				requestBytes.length, "application/json; charset=utf-8"); // 请求体
    		postMethod.setRequestEntity(requestEntity);
    		httpClient.executeMethod(postMethod);// 执行请求
    		InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
    		byte[] datas = null;
    		try {
    			datas = readInputStream(soapResponseStream);// 从输入流中读取数据
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		String result = new String(datas, "UTF-8");// 将二进制流转为String
    		// 打印返回结果
    		// System.out.println(result);
    
    		return result;
    
    	}
    
    	/**
    	 * 从输入流中读取数据
    	 * 
    	 * @param inStream
    	 * @return
    	 * @throws Exception
    	 */
    	public static byte[] readInputStream(InputStream inStream) throws Exception {
    		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    		byte[] buffer = new byte[1024];
    		int len = 0;
    		while ((len = inStream.read(buffer)) != -1) {
    			outStream.write(buffer, 0, len);
    		}
    		byte[] data = outStream.toByteArray();
    		outStream.close();
    		inStream.close();
    		return data;
    	}
    }
    

    例2: 来源:开源中国 teardream http://www.oschina.net/code/snippet_2266157_45252

    import java.io.BufferedReader;  
    import java.io.IOException;
    import java.io.InputStream;  
    import java.io.InputStreamReader;  
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;  
    import java.net.HttpURLConnection;  
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import java.net.URL; 
    import java.net.URLConnection;
    import java.util.List;
    import java.util.Map;
     
    /** 
     * Http请求工具类 
     * @author snowfigure 
     * @since 2014-8-24 13:30:56 
     * @version v1.0.1 
     */
    public class HttpRequestUtil {
        static boolean proxySet = false;
        static String proxyHost = "127.0.0.1";
        static int proxyPort = 8087;
        /** 
         * 编码 
         * @param source 
         * @return 
         */ 
        public static String urlEncode(String source,String encode) {  
            String result = source;  
            try {  
                result = java.net.URLEncoder.encode(source,encode);  
            } catch (UnsupportedEncodingException e) {  
                e.printStackTrace();  
                return "0";  
            }  
            return result;  
        }
        public static String urlEncodeGBK(String source) {  
            String result = source;  
            try {  
                result = java.net.URLEncoder.encode(source,"GBK");  
            } catch (UnsupportedEncodingException e) {  
                e.printStackTrace();  
                return "0";  
            }  
            return result;  
        }
        /** 
         * 发起http请求获取返回结果 
         * @param req_url 请求地址 
         * @return 
         */ 
        public static String httpRequest(String req_url) {
            StringBuffer buffer = new StringBuffer();  
            try {  
                URL url = new URL(req_url);  
                HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
       
                httpUrlConn.setDoOutput(false);  
                httpUrlConn.setDoInput(true);  
                httpUrlConn.setUseCaches(false);  
       
                httpUrlConn.setRequestMethod("GET");  
                httpUrlConn.connect();  
       
                // 将返回的输入流转换成字符串  
                InputStream inputStream = httpUrlConn.getInputStream();  
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
       
                String str = null;  
                while ((str = bufferedReader.readLine()) != null) {  
                    buffer.append(str);  
                }  
                bufferedReader.close();  
                inputStreamReader.close();  
                // 释放资源  
                inputStream.close();  
                inputStream = null;  
                httpUrlConn.disconnect();  
       
            } catch (Exception e) {  
                System.out.println(e.getStackTrace());  
            }  
            return buffer.toString();  
        }  
           
        /** 
         * 发送http请求取得返回的输入流 
         * @param requestUrl 请求地址 
         * @return InputStream 
         */ 
        public static InputStream httpRequestIO(String requestUrl) {  
            InputStream inputStream = null;  
            try {  
                URL url = new URL(requestUrl);  
                HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
                httpUrlConn.setDoInput(true);  
                httpUrlConn.setRequestMethod("GET");  
                httpUrlConn.connect();  
                // 获得返回的输入流  
                inputStream = httpUrlConn.getInputStream();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return inputStream;  
        }
         
         
        /**
         * 向指定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 的形式。
         * @param isproxy
         *               是否使用代理模式
         * @return 所代表远程资源的响应结果
         */
        public static String sendPost(String url, String param,boolean isproxy) {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                HttpURLConnection conn = null;
                if(isproxy){//使用代理模式
                    @SuppressWarnings("static-access")
                    Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                    conn = (HttpURLConnection) realUrl.openConnection(proxy);
                }else{
                    conn = (HttpURLConnection) realUrl.openConnection();
                }
                // 打开和URL之间的连接
                 
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");    // POST方法
                 
                 
                // 设置通用的请求属性
                 
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                 
                conn.connect();
                 
                // 获取URLConnection对象对应的输出流
                out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                // 发送请求参数
                out.write(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;
        }    
         
        public static void main(String[] args) {
            //demo:代理访问
            String url = "http://api.adf.ly/api.php";
            String para = "key=youkeyid&youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com";
             
            String sr=HttpRequestUtil.sendPost(url,para,true);
            System.out.println(sr);
        }
         
    }
    
    
    

    例3

    /**
    	 * 发送Http post请求
    	 * 
    	 * @param xmlInfo
    	 *            json转化成的字符串
    	 * @param URL
    	 *            请求url
    	 * @return 返回信息
    	 */
    	public static String doHttpPost(String xmlInfo, String URL) {
    		System.out.println("发起的数据:" + xmlInfo);
    		byte[] xmlData = xmlInfo.getBytes();
    		InputStream instr = null;
    		java.io.ByteArrayOutputStream out = null;
    		try {
    			URL url = new URL(URL);
    			URLConnection urlCon = url.openConnection();
    			urlCon.setDoOutput(true);
    			urlCon.setDoInput(true);
    			urlCon.setUseCaches(false);
    			urlCon.setRequestProperty("content-Type", "application/json");
    			urlCon.setRequestProperty("charset", "utf-8");
    			urlCon.setRequestProperty("Content-length",
    					String.valueOf(xmlData.length));
    			System.out.println(String.valueOf(xmlData.length));
    			DataOutputStream printout = new DataOutputStream(
    					urlCon.getOutputStream());
    			printout.write(xmlData);
    			printout.flush();
    			printout.close();
    			instr = urlCon.getInputStream();
    			byte[] bis = IOUtils.toByteArray(instr);
    			String ResponseString = new String(bis, "UTF-8");
    			if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
    				System.out.println("返回空");
    			}
    			System.out.println("返回数据为:" + ResponseString);
    			return ResponseString;
    
    		} catch (Exception e) {
    			e.printStackTrace();
    			return "0";
    		} finally {
    			try {
    				out.close();
    				instr.close();
    
    			} catch (Exception ex) {
    				return "0";
    			}
    		}
    	}
    
    展开全文
  • java发送HTTP

    2009-04-13 09:06:00
    URL url = new URL("http://"... 发送请求的URL HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); BufferedOutputStream hurlBufOus = null;

    URL url = new URL("http://"); 发送请求的URL

     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       conn.setDoOutput(true);
       conn.setDoInput(true);
       BufferedOutputStream hurlBufOus = null;
       if (postData != null && !("").equals(postData)) { //参数
        hurlBufOus = new BufferedOutputStream(conn.getOutputStream());
        hurlBufOus.write(postData.getBytes());
        hurlBufOus.flush();
       }
       conn.connect();
       BufferedReader br = new BufferedReader(
         new java.io.InputStreamReader(conn.getInputStream()));
       StringBuffer sb = new StringBuffer("");
       String tmp = "";
       while ((tmp = br.readLine()) != null) {//响应
        sb.append(tmp);
       }

    展开全文
  • 详解Java发送HTTP请求

    2020-08-26 04:10:57
    主要介绍了Java发送HTTP请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • java发送http请求

    2016-05-09 16:29:51
    java发送http请求的一个小例子 包含get和post两种请求方式
  • java发送http请求报文json
  • 本文通过实例代码给大家介绍了Java 发送http请求上传文件功能,需要的朋友参考下吧
  • 完整的java发送http包工程,可发送get及post请求。
  • java 发送HTTP请求工具

    2017-08-02 16:15:17
    java 发送HTTP请求工具
    package xx.xx.xx;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import org.apache.commons.lang.StringUtils;
    
    /**
     * 发送http请求工具
     *
     * @author Shi Zezhu
     * @date 2016年10月24日 下午5:01:06
     */
    public class ConnectionUtils {
        /**
         * 请求类型:GET
         */
        public static final String HTTP_TYPE_GET = "GET";
        /**
         * 请求类型:POST
         */
        public static final String HTTP_TYPE_POST = "POST";
    
        /**
         * 发送http请求
         *
         * @param urlString
         *            url地址
         * @param method
         *            请求类型
         * @param parameters
         *            请求参数
         * @return JSONObject string
         * @throws IOException
         */
        private static String send(String urlString, String method, String data) throws IOException {
            if (StringUtils.isBlank(urlString) || StringUtils.isBlank(method)) {
                return null;
            }
            if (HTTP_TYPE_GET.equalsIgnoreCase(method) && StringUtils.isNotBlank(data)) {
                urlString = urlString + "?" + data;
            }
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);// 设置请求方法
            connection.setDoInput(true);// 设置是否使用输入流
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(5 * 1000);
            
            if (HTTP_TYPE_POST.equalsIgnoreCase(method) && StringUtils.isNotBlank(data)) {
                connection.setDoOutput(true);// 设置是否使用输出流
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
                out.write(data);
                out.flush();
                out.close();
            }
            InputStream is = null;
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }
            if (is == null) {
                return "";
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            connection.disconnect();
            return sb.toString();
        }
    
        public static String mapToParamStr(Map<String, String> parameters) {
            String data = "";
            if (parameters != null && parameters.size() > 0) {
                int i = 0;
                StringBuilder sb = new StringBuilder();
                for (Entry<String, String> entry : parameters.entrySet()) {
                    if (i > 0) {
                        sb.append("&");
                    }
                    sb.append(entry.getKey()).append("=").append(entry.getValue());
                    i++;
                }
                data = sb.toString();
            }
            return data;
        }
    
        /**
         * 发送get请求
         *
         * @param urlString
         * @param parameters
         * @return
         * @throws IOException
         */
        public static String sendGet(String url, Map<String, String> parameters) throws IOException {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            return send(url, HTTP_TYPE_GET, mapToParamStr(parameters));
        }
        
        /**
         * 发送get请求
         *
         * @param urlString
         * @param paramStr
         * @return
         * @throws IOException
         */
        public static String sendGet(String url, String paramStr) throws IOException {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            return send(url, HTTP_TYPE_GET, paramStr);
        }
    
        /**
         * 发送get请求
         *
         * @param urlString
         * @return
         * @throws IOException
         */
        public static String sendGet(String url) throws IOException {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            return send(url, HTTP_TYPE_GET, null);
        }
    
        /**
         * 发送post请求
         *
         * @param urlString
         * @param parameters
         * @return
         * @throws IOException
         */
        public static String sendPost(String url, Map<String, String> parameters) throws IOException {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            return send(url, HTTP_TYPE_POST, mapToParamStr(parameters));
        }
        
        /**
         * 发送post请求
         *
         * @param urlString
         * @param paramStr
         * @return
         * @throws IOException
         */
        public static String sendPost(String url, String paramStr) throws IOException {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            return send(url, HTTP_TYPE_POST, paramStr);
        }
    
        /**
         * 发送post请求
         *
         * @param urlString
         * @return
         * @throws IOException
         */
        public static String sendPost(String url) throws IOException {
            if (StringUtils.isBlank(url)) {
                return null;
            }
            return send(url, HTTP_TYPE_POST, null);
        }
    }


    展开全文
  • 主要为大家详细介绍了java发送http get请求的两种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 主要介绍了JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码,需要的朋友可以参考下
  • JAVA发送HTTP请求方式总结

    万次阅读 多人点赞 2018-05-30 14:40:21
    java 发送HTTP请求方式总结 源代码:http://github.com/lovewenyo/HttpDemo 1. HttpURLConnection 使用JDK原生提供的net,无需其他jar包; HttpURLConnection是URLConnection的子类,提供更多的方法,...

    java 发送HTTP请求方式总结

    源代码:http://github.com/lovewenyo/HttpDemo

    1. HttpURLConnection

    使用JDK原生提供的net,无需其他jar包;

    HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

    package httpURLConnection;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class HttpURLConnectionHelper {
    
        public static String sendRequest(String urlParam,String requestType) {
    
            HttpURLConnection con = null;  
    
            BufferedReader buffer = null; 
            StringBuffer resultBuffer = null;  
    
            try {
                URL url = new URL(urlParam); 
                //得到连接对象
                con = (HttpURLConnection) url.openConnection(); 
                //设置请求类型
                con.setRequestMethod(requestType);  
                //设置请求需要返回的数据类型和字符集类型
                con.setRequestProperty("Content-Type", "application/json;charset=GBK");  
                //允许写出
                con.setDoOutput(true);
                //允许读入
                con.setDoInput(true);
                //不使用缓存
                con.setUseCaches(false);
                //得到响应码
                int responseCode = con.getResponseCode();
    
                if(responseCode == HttpURLConnection.HTTP_OK){
                    //得到响应流
                    InputStream inputStream = con.getInputStream();
                    //将响应流转换成字符串
                    resultBuffer = new StringBuffer();
                    String line;
                    buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                    while ((line = buffer.readLine()) != null) {
                        resultBuffer.append(line);
                    }
                    return resultBuffer.toString();
                }
    
            }catch(Exception e) {
                e.printStackTrace();
            }
            return "";
        }
        public static void main(String[] args) {
    
            String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
            System.out.println(sendRequest(url,"POST"));
        }
    }
    

    2. URLConnection

    使用JDK原生提供的net,无需其他jar包;

    建议使用HttpURLConnection

    package uRLConnection;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class URLConnectionHelper {
    
        public static String sendRequest(String urlParam) {
    
            URLConnection con = null;  
    
            BufferedReader buffer = null; 
            StringBuffer resultBuffer = null;  
    
            try {
                 URL url = new URL(urlParam); 
                 con = url.openConnection();  
    
                //设置请求需要返回的数据类型和字符集类型
                con.setRequestProperty("Content-Type", "application/json;charset=GBK");  
                //允许写出
                con.setDoOutput(true);
                //允许读入
                con.setDoInput(true);
                //不使用缓存
                con.setUseCaches(false);
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
    
            }catch(Exception e) {
                e.printStackTrace();
            }
    
            return "";
        }
        public static void main(String[] args) {
            String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
            System.out.println(sendRequest(url));
        }
    }
    

    3. HttpClient

    使用方便,我个人偏爱这种方式,但依赖于第三方jar包,相关maven依赖如下:

    <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency
    

    package httpClient;
    
    import java.io.IOException;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    public class HttpClientHelper {
        public static String sendPost(String urlParam) throws HttpException, IOException {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建post请求方法实例对象
            PostMethod postMethod = new PostMethod(urlParam);
            // 设置post请求超时时间
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            postMethod.addRequestHeader("Content-Type", "application/json");
    
            httpClient.executeMethod(postMethod);
    
            String result = postMethod.getResponseBodyAsString();
            postMethod.releaseConnection();
            return result;
        }
        public static String sendGet(String urlParam) throws HttpException, IOException {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建GET请求方法实例对象
            GetMethod getMethod = new GetMethod(urlParam);
            // 设置post请求超时时间
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            getMethod.addRequestHeader("Content-Type", "application/json");
    
            httpClient.executeMethod(getMethod);
    
            String result = getMethod.getResponseBodyAsString();
            getMethod.releaseConnection();
            return result;
        }
        public static void main(String[] args) throws HttpException, IOException {
            String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
            System.out.println(sendPost(url));
            System.out.println(sendGet(url));
        }
    }
    

    4. Socket

    使用JDK原生提供的net,无需其他jar包;

    使用起来有点麻烦。

    package socket;
    import java.io.BufferedInputStream;  
    import java.io.BufferedReader;  
    import java.io.BufferedWriter;  
    import java.io.IOException;  
    import java.io.InputStreamReader;  
    import java.io.OutputStreamWriter;  
    import java.net.Socket;  
    import java.net.URLEncoder;  
    
    import javax.net.ssl.SSLSocket;  
    import javax.net.ssl.SSLSocketFactory;  
    
    public class SocketForHttpTest {  
    
        private int port;  
        private String host;  
        private Socket socket;  
        private BufferedReader bufferedReader;  
        private BufferedWriter bufferedWriter;  
    
        public SocketForHttpTest(String host,int port) throws Exception{  
    
            this.host = host;  
            this.port = port;  
    
            /**  
             * http协议  
             */  
            // socket = new Socket(this.host, this.port);  
    
            /**  
             * https协议  
             */  
            socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port);  
    
    
        }  
    
        public void sendGet() throws IOException{  
            //String requestUrlPath = "/z69183787/article/details/17580325";  
            String requestUrlPath = "/";          
    
            OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());    
            bufferedWriter = new BufferedWriter(streamWriter);              
            bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");    
            bufferedWriter.write("Host: " + this.host + "\r\n");    
            bufferedWriter.write("\r\n");    
            bufferedWriter.flush();    
    
            BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    
            bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    
            String line = null;    
            while((line = bufferedReader.readLine())!= null){    
                System.out.println(line);    
            }    
            bufferedReader.close();    
            bufferedWriter.close();    
            socket.close();  
    
        }  
    
    
        public void sendPost() throws IOException{    
                String path = "/";    
                String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("张三", "utf-8") + "&" +    
                            URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");    
                // String data = "name=zhigang_jia";    
                System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);              
                OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");    
                bufferedWriter = new BufferedWriter(streamWriter);                  
                bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");    
                bufferedWriter.write("Host: " + this.host + "\r\n");    
                bufferedWriter.write("Content-Length: " + data.length() + "\r\n");    
                bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");    
                bufferedWriter.write("\r\n");    
                bufferedWriter.write(data);    
    
                bufferedWriter.write("\r\n");    
                bufferedWriter.flush();    
    
                BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());    
                bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));    
                String line = null;    
                while((line = bufferedReader.readLine())!= null)    
                {    
                    System.out.println(line);    
                }    
                bufferedReader.close();    
                bufferedWriter.close();    
                socket.close();    
        }    
    
        public static void main(String[] args) throws Exception {  
            /**  
             * http协议测试  
             */  
            //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80);  
            /**  
             * https协议测试  
             */  
            SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443);  
            try {  
                forHttpTest.sendGet();  
            //  forHttpTest.sendPost();  
            } catch (IOException e) {  
    
                e.printStackTrace();  
            }  
        }  
    
    }  
    
    展开全文
  • 主要介绍了Java发送http get/post请求调用接口/方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • JAVA发送HTTP请求与处理参考: http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html http://blog.csdn.net/atco/article/details/7949210  http://www.oschina.net/code/snippet_582384_44785 ...
  • java发送http请求的两种方式:HTTPClient和CloseableHttpClient 下面分别介绍使用HTTPClient和CloseableHTTPClient进行Get和Post请求的方式。 HttpClient 使用commons-httpclient.jar,maven依赖如下: &lt;...
  • 转自:java发送http的get、post请求 Http请求类 package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java...
  • JAVA发送HTTP请求操作类 HttpRequester request = new HttpRequester(); HttpRespons hr = request.sendPost("响应地址", 参数Map);//有重载,可设置请求头、请求体 hr获得回执内容
  • Java发送Http请求,解析html返回
  • Java发送Http请求的一般步骤

    千次阅读 2019-04-29 14:51:41
    Java发送Http请求的一般步骤 最近在使用百度地图和百度AI的开发API,经常需要发送http请求,在这里记录一下java发送Http请求的步骤。希望对大家有用。 了解Http报文结构 首先介绍Http协议的结构。请求报文和响应...
  • java 发送http请求

    2014-11-11 10:51:21
    java发送http请求 最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet。post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求...
  • 下面小编就为大家带来一篇java发送http get请求的两种方法(总结)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • java发送http的post请求

    2016-11-14 14:26:02
    java发送http的get、post请求Http请求类 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net....
  • JAVA发送HTTP请求,返回HTTP响应内容
  • Java 发送http请求,上传文件

    千次阅读 2017-06-06 20:41:49
    Java 发送http请求,post 上传文件
  • java发送http/https请求(get/post)代码,java 通过发送json,post请求,返回json数据的方法 java 通过发送json,post请求,返回json数据的方法

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 10,319
精华内容 4,127
关键字:

java发送http

java 订阅