A brief introduction to HTTP requests in Java Network programming _java

Source: Internet
Author: User

Details of the HTTP request--Request Line

The get in the request line is called the request method: Post,, OPTIONS, deletes, TRACE, put, commonly used: Got, post
If users do not have settings, by default, the browser to send to the server is a GET request, such as in the browser directly address access, point hyperlink access, etc. are get, users want to change the way the request to post, can be implemented by changing the form of submission.
Whether post or get is used to request a Web resource from the server, the difference is primarily in data delivery: If the request is a GET method, it can be followed by the requested URL address. In the form of data that is given to the server, separated by &, For example: get/mail/1.html?name=abc&password=xyz http/1.1
The feature of Get mode: The parameters that come with the URL address are limited, and the data capacity is usually not more than 1K.
If the request is post, you can send data to the server in the requested entity content, which is characterized by a post that has no limit on the amount of data being transmitted.

Details of the HTTP request--Message headers


Common message headers in HTTP requests

Accept: The browser uses this header to tell the server what type of data it supports
Accept-charset: The browser tells the server through this header which character set it supports
Accept-encoding: The browser tells the server through this header that the supported compression formats
Accept-language: The browser tells the server through this header that its locale
Host: The browser uses this header to tell the server which host you want to access
If-modified-since: The browser tells the server through this header, the time that the data is cached
Referer: The browser through this head to tell the server, the client is which page to the anti-theft chain
Connection: The browser through this head to tell the server, after the request is disconnected or where the link

Cases:

Http_get

Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.net.HttpURLConnection; 
Import java.net.MalformedURLException; 
 
 
Import Java.net.URL; 
 
  public class Http_get {private static String Url_path = "Yun_qi_img/pro1.png"; Public Http_get () {//TODO auto-generated constructor stub} public static void Saveimagetodisk () {INP 
    Utstream InputStream = getInputStream (); 
    byte[] data = new byte[1024]; 
    int len = 0; 
    FileOutputStream fileoutputstream = null; 
      try {fileoutputstream = new FileOutputStream ("C:\\test.png"); 
      while (len = inputstream.read (data))!=-1) {fileoutputstream.write (data, 0, Len); 
    The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
        finally {if (InputStream!= null) {try {inputstream.close (); catch (IOException e) {//TODO auto-generated Catch block E.printstacktrace (); 
        } if (FileOutputStream!= null) {try {fileoutputstream.close (); 
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); /** * Obtains server-side data and returns * @return/public static InputStream Getinpu in InputStream form 
    Tstream () {InputStream inputstream = null; 
    HttpURLConnection httpurlconnection = null; 
      try {URL url = new URL (url_path); 
        if (URL!= null) {httpurlconnection = (httpurlconnection) url.openconnection (); 
        Set timeout for connection network httpurlconnection.setconnecttimeout (3000); 
        Httpurlconnection.setdoinput (TRUE); 
        Indicates that this HTTP request is set to request Httpurlconnection.setrequestmethod ("get") using a Get method; 
        int responsecode = Httpurlconnection.getresponsecode (); if (Responsecode = = 200) {//Gets an input stream from the server InputStream = Httpurlconnection.getinputstream (); 
    (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
  return inputstream; 
  public static void Main (string[] args) {//Get picture from server to save to local saveimagetodisk (); 

 } 
}

http_post

Import Java.io.ByteArrayOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import Java.io.OutputStream; 
Import java.io.UnsupportedEncodingException; 
Import java.net.HttpURLConnection; 
Import java.net.MalformedURLException; 
Import Java.net.URL; 
Import Java.net.URLEncoder; 
Import Java.util.HashMap; 
 
Import Java.util.Map; public class Http_post {//Request server-side URL private static String PATH = "Http://192.168.1.125:8080/myhttp/servlet/Logi 
  Naction "; 
 
  private static URL URL; Public Http_post () {//TODO auto-generated constructor stub} static {try {url = new URL (PATH) 
    ; 
    catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); }/** * @param params * The parameters of the URL that are filled in * @param encode * byte code * @return/Publi 
C static String Sendpostmessage (Map<string, string> params, string encode) {//as StringBuffer initialized string    StringBuffer buffer = new StringBuffer (); try {if (params!= null &&!params.isempty ()) {for (map.entry<string, string> Entry:par Ams.entryset ()) {//complete transcoding operation Buffer.append (Entry.getkey ()). Append ("="). Append (U 
          Rlencoder.encode (Entry.getvalue (), encode)). Append ("&"); 
      } Buffer.deletecharat (Buffer.length ()-1); 
      }//System.out.println (buffer.tostring ()); 
      Delete the most one & System.out.println ("-->>" +buffer.tostring ()); 
      HttpURLConnection URLConnection = (httpurlconnection) URL. OpenConnection (); 
      Urlconnection.setconnecttimeout (3000); 
      Urlconnection.setrequestmethod ("POST");  
      Urlconnection.setdoinput (TRUE);//means getting data from the server Urlconnection.setdooutput (TRUE);//To write data to the server//Get upload information byte size and length 
      byte[] MyData = buffer.tostring (). GetBytes (); Indicates that the type of the set request body is a text type UrlconnectIon.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); 
      Urlconnection.setrequestproperty ("Content-length", String.valueof (Mydata.length)); 
      Get output stream, output data to server OutputStream OutputStream = Urlconnection.getoutputstream (); 
      Outputstream.write (mydata,0,mydata.length); 
      Outputstream.close (); 
      Obtain the results of the server response and status code int responsecode = Urlconnection.getresponsecode (); 
      if (Responsecode = =) {return Changeinputstream (Urlconnection.getinputstream (), encode); 
    The catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace (); 
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
  Return ""; /** * Converts an input stream to the specified encoded string * * @param inputstream * @param encode * @return * * Private stat IC string Changeinputstream (InputStream inputstream, string enCode) {//TODO auto-generated method stub Bytearrayoutputstream outputstream = new Bytearrayoutputstream (); 
    byte[] data = new byte[1024]; 
    int len = 0; 
    String result = ""; if (InputStream!= null) {try {while (len = inputstream.read (data))!=-1) {OUTPUTSTREAM.WR 
        ITE (data, 0, Len); 
      result = new String (Outputstream.tobytearray (), encode); 
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
  } return result; 
    }/** * @param args */public static void main (string[] args) {//TODO auto-generated method stub 
    map<string, string> params = new hashmap<string, string> (); 
    Params.put ("username", "admin"); 
    Params.put ("password", "123"); 
    String result = Http_post.sendpostmessage (params, "utf-8"); 
  System.out.println ("--result->>" + result); 
 } 
 
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.