package com.grefr.basemethod;

/*JAVA send out HTTP request , return HTTP Response content , Examples and Applications Blog classification : JAVA Realization

Java.netBeanJDKApache .

JDK Some requests for stateless protocols are provided in (HTTP ) Support for , Now I'm going to give you a little example of what I wrote ( Components ) Describe :

First, let's build a request class (HttpRequester ).

This class encapsulates JAVA Code to implement simple requests , as follows : */

//Java Code

import java.io.BufferedReader; 

import java.io.IOException; 

import java.io.InputStream; 

import java.io.InputStreamReader; 

import java.net.HttpURLConnection; 

import java.net.URL; 

import java.nio.charset.Charset; 

import java.util.Map; 

import java.util.Vector; 

  

/**

* HTTP Request object



* @author YYmmiinngg

*/

public class HttpRequester { 

    private String defaultContentEncoding; 

  

    public HttpRequester() { 

        this.defaultContentEncoding = Charset. defaultCharset().name(); 

    } 

  

    /**

     * send out GET request

     * 

     * @param urlString

     *            URL Address

     * @return The response object

     * @throws IOException

     */ 

    public HttpRespons sendGet(String urlString) throws IOException { 

        return this.send(urlString, "GET", null, null); 

    } 

  

    /**

     * send out GET request

     * 

     * @param urlString

     *            URL Address

     * @param params

     *            Parameter set

     * @return The response object

     * @throws IOException

     */ 

    public HttpRespons sendGet(String urlString, Map<String, String> params) 

            throws IOException { 

        return this.send(urlString, "GET", params, null); 

    } 

  

    /**

     * send out GET request

     * 

     * @param urlString

     *            URL Address

     * @param params

     *            Parameter set

     * @param propertys

     *            Request properties

     * @return The response object

     * @throws IOException

     */ 

    public HttpRespons sendGet(String urlString, Map<String, String> params, 

            Map<String, String> propertys) throws IOException { 

        return this.send(urlString, "GET", params, propertys); 

    } 

  

    /**

     * send out POST request

     * 

     * @param urlString

     *            URL Address

     * @return The response object

     * @throws IOException

     */ 

    public HttpRespons sendPost(String urlString) throws IOException { 

        return this.send(urlString, "POST", null, null); 

    } 

  

    /**

     * send out POST request

     * 

     * @param urlString

     *            URL Address

     * @param params

     *            Parameter set

     * @return The response object

     * @throws IOException

     */ 

    public HttpRespons sendPost(String urlString, Map<String, String> params) 

            throws IOException { 

        return this.send(urlString, "POST", params, null); 

    } 

  

    /**

     * send out POST request

     * 

     * @param urlString

     *            URL Address

     * @param params

     *            Parameter set

     * @param propertys

     *            Request properties

     * @return The response object

     * @throws IOException

     */ 

    public HttpRespons sendPost(String urlString, Map<String, String> params, 

            Map<String, String> propertys) throws IOException { 

        return this.send(urlString, "POST", params, propertys); 

    } 

  

    /**

     * send out HTTP request

     * 

     * @param urlString

     * @return Echo object

     * @throws IOException

     */ 

    private HttpRespons send(String urlString, String method, 

            Map<String, String> parameters, Map<String, String> propertys) 

            throws IOException { 

        HttpURLConnection urlConnection = null; 

  

        if (method.equalsIgnoreCase("GET") && parameters != null) { 

            StringBuffer param = new StringBuffer(); 

            int i = 0; 

            for (String key : parameters.keySet()) { 

                if (i == 0) 

                    param.append( "?"); 

                else

                    param.append( "&"); 

                param.append(key).append("=" ).append(parameters.get(key)); 

                i++; 

            } 

            urlString += param; 

        } 

        URL url = new URL(urlString); 

        urlConnection = (HttpURLConnection) url.openConnection(); 

  

        urlConnection.setRequestMethod(method); 

        urlConnection.setDoOutput( true); 

        urlConnection.setDoInput( true); 

        urlConnection.setUseCaches( false); 

  

        if (propertys != null) 

            for (String key : propertys.keySet()) { 

                urlConnection.addRequestProperty(key, propertys.get(key)); 

            } 

  

        if (method.equalsIgnoreCase("POST") && parameters != null) { 

            StringBuffer param = new StringBuffer(); 

            for (String key : parameters.keySet()) { 

                param.append( "&"); 

                param.append(key).append("=" ).append(parameters.get(key)); 

            } 

            urlConnection.getOutputStream().write(param.toString().getBytes()); 

            urlConnection.getOutputStream().flush(); 

            urlConnection.getOutputStream().close(); 

        } 

  

        return this.makeContent(urlString, urlConnection); 

    } 

  

    /**

     * Get the response object

     * 

     * @param urlConnection

     * @return The response object

     * @throws IOException

     */ 

    private HttpRespons makeContent(String urlString, 

            HttpURLConnection urlConnection) throws IOException { 

        HttpRespons httpResponser = new HttpRespons(); 

        try { 

            InputStream in = urlConnection.getInputStream(); 

            BufferedReader bufferedReader = new BufferedReader( 

                    new InputStreamReader(in)); 

            httpResponser. contentCollection = new Vector<String>(); 

            StringBuffer temp = new StringBuffer(); 

            String line = bufferedReader.readLine(); 

            while (line != null) { 

                httpResponser. contentCollection.add(line); 

                temp.append(line).append( "\r\n"); 

                line = bufferedReader.readLine(); 

            } 

            bufferedReader.close(); 

  

            String ecod = urlConnection.getContentEncoding(); 

            if (ecod == null) 

                ecod = this.defaultContentEncoding; 

  

            httpResponser. urlString = urlString; 

  

            httpResponser. defaultPort = urlConnection.getURL().getDefaultPort(); 

            httpResponser. file = urlConnection.getURL().getFile(); 

            httpResponser. host = urlConnection.getURL().getHost(); 

            httpResponser. path = urlConnection.getURL().getPath(); 

            httpResponser. port = urlConnection.getURL().getPort(); 

            httpResponser. protocol = urlConnection.getURL().getProtocol(); 

            httpResponser. query = urlConnection.getURL().getQuery(); 

            httpResponser. ref = urlConnection.getURL().getRef(); 

            httpResponser. userInfo = urlConnection.getURL().getUserInfo(); 

  

            httpResponser. content = new String(temp.toString().getBytes(), ecod); 

            httpResponser. contentEncoding = ecod; 

            httpResponser. code = urlConnection.getResponseCode(); 

            httpResponser. message = urlConnection.getResponseMessage(); 

            httpResponser. contentType = urlConnection.getContentType(); 

            httpResponser. method = urlConnection.getRequestMethod(); 

            httpResponser. connectTimeout = urlConnection.getConnectTimeout(); 

            httpResponser. readTimeout = urlConnection.getReadTimeout(); 

  

            return httpResponser; 

        } catch (IOException e) { 

            throw e; 

        } finally { 

            if (urlConnection != null) 

                urlConnection.disconnect(); 

        } 

    } 

  

    /**

     * The default response character set

     */ 

    public String getDefaultContentEncoding() { 

        return this.defaultContentEncoding; 

    } 

  

    /**

     * Set the default response character set

     */ 

    public void setDefaultContentEncoding(String defaultContentEncoding) { 

        this.defaultContentEncoding = defaultContentEncoding; 

    } 

}

/* Second, let's look at the response object (HttpRespons ). The response object is just data BEAN , This encapsulates the result data of the request response , as follows :

java Code   */

import java.util.Vector; 

  

/**

* The response object

*/

public class HttpRespons { 

  

    String urlString; 

  

   int defaultPort; 

 

   String file; 

 

   String host; 

 

   String path; 

 

   int port; 

 

   String protocol; 

 

   String query; 

 

   String ref; 

 

   String userInfo; 

 

   String contentEncoding; 

 

   String content; 

 

   String contentType; 

 

   int code; 

 

   String message; 

 

   String method; 

 

   int connectTimeout; 

 

   int readTimeout; 

 

   Vector<String> contentCollection; 

 

   public String getContent() { 

       return content; 

   } 

 

   public String getContentType() { 

       return contentType; 

   } 

 

   public int getCode() { 

       return code; 

   } 

 

   public String getMessage() { 

       return message; 

   } 

 

   public Vector<String> getContentCollection() { 

       return contentCollection; 

   } 

 

   public String getContentEncoding() { 

       return contentEncoding; 

   } 

 

   public String getMethod() { 

       return method; 

   } 

 

   public int getConnectTimeout() { 

       return connectTimeout; 

   } 

 

   public int getReadTimeout() { 

       return readTimeout; 

   } 

 

   public String getUrlString() { 

       return urlString; 

   } 

 

   public int getDefaultPort() { 

       return defaultPort; 

   } 

 

   public String getFile() { 

       return file; 

   } 

 

   public String getHost() { 

       return host; 

   } 

 

   public String getPath() { 

       return path; 

    } 

  

    public int getPort() { 

        return port; 

    } 

  

    public String getProtocol() { 

        return protocol; 

    } 

  

    public String getQuery() { 

        return query; 

    } 

  

    public String getRef() { 

        return ref; 

    } 

  

    public String getUserInfo() { 

        return userInfo; 

    } 

  

}

import java.util.Vector;

*//**

* The response object

*//*

public class HttpRespons {

String urlString;

int defaultPort;

String file;

String host;

String path;

int port;

String protocol;

String query;

String ref;

String userInfo;

String contentEncoding;

String content;

String contentType;

int code;

String message;

String method;

int connectTimeout;

int readTimeout;

Vector<String> contentCollection;

public String getContent() {

             return content;

      }

public String getContentType() {

             return contentType;

      }

public int getCode() {

             return code;

      }

public String getMessage() {

             return message;

      }

public Vector<String> getContentCollection() {

             return contentCollection;

      }

public String getContentEncoding() {

             return contentEncoding;

      }

public String getMethod() {

             return method;

      }

public int getConnectTimeout() {

             return connectTimeout;

      }

public int getReadTimeout() {

             return readTimeout;

      }

public String getUrlString() {

             return urlString;

      }

public int getDefaultPort() {

             return defaultPort;

      }

public String getFile() {

             return file;

      }

public String getHost() {

             return host;

      }

public String getPath() {

             return path;

      }

public int getPort() {

             return port;

      }

public String getProtocol() {

             return protocol;

      }

public String getQuery() {

             return query;

      }

public String getRef() {

             return ref;

      }

public String getUserInfo() {

             return userInfo;

      }

}

Last , Let's write an application class , Test whether the above code is correct

Java Code

import com.yao.http.HttpRequester; 

import com.yao.http.HttpRespons; 

  

public class Test { 

    public static void main(String[] args) { 

        try { 

            HttpRequester request = new HttpRequester(); 

            HttpRespons hr = request.sendGet( "http://www.csdn.net"); 

 

            System. out.println(hr.getUrlString()); 

            System. out.println(hr.getProtocol()); 

            System. out.println(hr.getHost()); 

            System. out.println(hr.getPort()); 

            System. out.println(hr.getContentEncoding()); 

            System. out.println(hr.getMethod()); 

             

            System. out.println(hr.getContent()); 

  

        } catch (Exception e) { 

            e.printStackTrace(); 

        } 

    } 

}

HTTP Ask for more articles about examples

  1. URLConnection and HttpClients Send request example

    . java.net.URLConnection package test; import java.io.BufferedReader; import java.io.IOException; im ...

  2. URLConnection and HttpClients Send request example 【 primary 】

    note , Not fully standardized . java.net.URLConnection package test; import java.io.BufferedReader; import java.io.IOExcep ...

  3. Why I choose to use Retrofit As my network request framework

    Compare AsyncTask.Volley.Retrofit The request time of the three Use A single request 7 A request 25 A request AsyncTask 941ms 4539ms 13957ms Volley 560ms 22 ...

  4. window apidoc Installation and use

    apidoc It's a lightweight online REST Interface document generation system , Support multiple mainstream languages , Include Java.C.C#.PHP and Javascript etc. . Users only need to write notes as required , You can generate a good readability . On line connection with beautiful interface ...

  5. Hadoop Study ( Two ) Hadoop Detailed explanation of configuration file parameters

    Hadoop Operation mode is divided into safe mode and non safe mode , ad locum , I'm going to talk about non secure mode , Important parameters, functions and functions of main configuration files , Used in this article Hadoop Version is 2.6.4. etc/hadoop/core-site.xm ...

  6. Hadoop Intro - Configure

    Hadoop Study ( Two ) Hadoop Detailed explanation of configuration file parameters   Hadoop Operation mode is divided into safe mode and non safe mode , ad locum , I'm going to talk about non secure mode , Important parameters, functions and functions of main configuration files , Used in this article Hadoop Version is 2 ...

  7. 【LoadRunner】 How to GIS Server performance test

    1. Need understanding First, make sure that gis Test scope of server pressure test , Form specific test cases ,gis The platform is all through the web javascript api Called gis Cluster service interface , adopt LR Record the business operation in the previous step , find javasc ...

  8. Zhao Yazhi :android teaching program

    Underline the link address for details . Click to jump . I hope I can do something for you . It's still being sorted out Teaching chapters Content of courses Class hour arrangement remarks 1 Android High speed entry 2 Android Simulators and common commands 3 Androi ...

  9. apidoc Fast generation of interface document

    Official document link :http://apidocjs.com/#demo apidoc It's a lightweight online REST Interface document generation system , Support multiple mainstream languages , Include Java.C.C#.PHP and Javascript etc. . Use ...

Random recommendation

  1. js Real time monitoring input The median change

    Be careful : Yes jquery Need to introduce jquery.min.js. demand : 1. Each place needs to be scored separately , The total score is 100; 2. The first total score is 40; 3. The second total score is 60. Be careful : You need to determine null.&quo ...

  2. Lucene.net On-site search —6、 Search the second edition of the website

    Catalog Lucene.net On-site search —1.SEO Optimize Lucene.net On-site search —2.Lucene.Net Introduction and participle Lucene.net On-site search —3. The simplest search engine code Lucene.net On-site search —4 ...

  3. Object C Learning notes 25- file management ( One )

    In this article, a brief record of file management , stay Object C in NSFileManager Used to manage file paths . stay Object C The file path in can be relative path or absolute path . Oblique line “/” start , The slash is actually an eye ...

  4. WPF Paragraph Get or modify text content

    One . explain Paragraph Inherited from Block,Block Inherited from TextElement, stay TextElement in // // Abstract : // Gets the... That represents the end of the content in the element System.Windows.Do ...

  5. uber Rewards and billing details

    In order to make it easy for car owners to understand the incentive policy and accounting method of bill details , We made it specially # Reward details # The special topic of , Make sure you have all the tips and tricks to understand the bill in five minutes . The first part : Income statement Is it dizzy to see the statement of income , Coming and coming , One of us ...

  6. 201521123048 《Java Programming 》 The first 12 Weekly learning summary

    1. This week's learning summary 1.1 In the way you like ( Mind mapping or something ) Summarize the multi stream and file related content . 2. Written work take Student object ( attribute :int id, String name,int age,doubl ...

  7. MySQL install (yum、 Binary system 、 Source code )

    MySQL install (yum. Binary system . Source code ) Catalog 1.1 yum install ... 2 1.2 Binary installation -mysql-5.7.17. 3 1.2.1 preparation ... 3 1.2.2 decompression . Move . to grant authorization ... 3 ...

  8. Linux Next jdk Environment configuration

    1. download jdk http://www.oracle.com/technetwork/java/javase/downloads/index.html I choose 64 Bit version jdk-8u121-linux ...

  9. solve html5 canvas Draw Fonts 、 Blurred picture and figure

    html5 canvas Draw Fonts . Blurred picture and figure What happened Most of them appear in high dpi equipment , That means more pixels per square inch , Such as mobile phone , The tablet . Of course, many high-end desktop computers also have high resolution dpi Display for . canva ...

  10. 20165214 2018-2019-2 《 Network countermeasure technology 》Exp1+ Reverse progression Week4

    < Network countermeasure technology >Exp2 PC Platform reverse cracking "MAL_ Simple back door " Week4 One . Experimental content Task1 Write your own 64 position shellcode. Reference resources shellcode To guide the ...