Java implementation HTTP protocol send receive data

Source: Internet
Author: User

Java simulation Post/get Way to send data the main method is in the post

Import java.io.*;
Import java.net.HttpURLConnection;
Import Java.net.URL;


Import Java.net.URLEncoder;

    public class Httpurl {private static final String TAG = "NetUtils"; /** * Use post to login * * @param username * @param password * @return/public static void M
        Ain (String []args) {Httpurl test=new httpurl ();
    Test.loginofpost ("Niha", "qwer1234");
        public static string Loginofpost (string username, string password) {HttpURLConnection conn = null;
            try {//Create a URL object url murl = new URL ("http://localhost:12001");

            Call the OpenConnection () method of the URL to get the HttpURLConnection object conn = (httpurlconnection) murl.openconnection (); Conn.setrequestmethod ("post"); The set request method is POST/* conn.setreadtimeout (5000);/set read timeout of 5 seconds Conn.set
     ConnectTimeout (10000);/Set Connection network timeout of 10 seconds/conn.setdooutput (true);/Set this method to allow output to the server int len=0;       String path= "E:\\private_project\\github_project\\nsar\\test.txt";
            The parameter of the POST request byte[] buf= new byte[10240];
            FileInputStream fis=new FileInputStream (path);
            while (len = Fis.read (buf))!=-1) {System.out.print (len);
            }//String data = "Username=" + username + "&password=" + password;            Obtains an output stream, writes the data to the server, by default, the system does not allow to output the content to the server outputstream out = Conn.getoutputstream ();//get an output stream, write data to the server/
            Out.write (Data.getbytes ());
            Out.write (BUF);
            Out.flush ();

            Out.close ();

                int responsecode = Conn.getresponsecode ()//Call this method eliminates the need to use the Conn.connect () method if (Responsecode = = 200) {
                InputStream is = Conn.getinputstream ();
                String state = Getstringfrominputstream (IS);
            return state;
                else {//LOG.I (TAG, "Access failed" + Responsecode); System.out.Print ("Access failed");
        } catch (Exception e) {e.printstacktrace (); finally {if (conn!= null) {conn.disconnect ();//Close Connection}} RET
    Urn null; /** * Use get way to login * * @param username * @param password * @return * * public static

        String Loginofget (string username, string password) {HttpURLConnection conn = null;
        String data = "Username=" + urlencoder.encode (username) + "&password=" + urlencoder.encode (password); String url = "Http://192.168.0.100:8080/android/servlet/LoginServlet?"
        + data;
            try {//Use string URL to build URL object url murl = new URL (URL);

            conn = (httpurlconnection) murl.openconnection ();
            Conn.setrequestmethod ("get");
            Conn.setreadtimeout (5000);

            Conn.setconnecttimeout (10000);
            int responsecode = Conn.getresponsecode (); if (rEsponsecode = = {InputStream is = Conn.getinputstream ();
                String state = Getstringfrominputstream (IS);
            return state;
                else {//LOG.I (TAG, "Access failed" + Responsecode);

            System.out.print ("Access failed");
        } catch (Exception e) {e.printstacktrace ();
            finally {if (conn!= null) {conn.disconnect ();
    } return null; /** * Returns a string message based on stream * * @param is * @return * @throws IOException/Private St atic String Getstringfrominputstream (InputStream is) throws IOException {Bytearrayoutputstream OS = n
        EW Bytearrayoutputstream ();
        Template code must be skilled byte[] buffer = new byte[1024];
        int len =-1;  Be sure to write Len=is.read (buffer)//if while ((Is.read (buffer))!=-1 cannot write data to the buffer while (len = is.read (buffer)
!=-1) {            Os.write (buffer, 0, Len);
        } is.close ();
        string state = Os.tostring ()//Converts the data in the stream to a string, using the encoding utf-8 (emulator default encoding) Os.close ();
    return state;

 }
}


Java simulation server-side receive Post/get data implementation does not need to return data to the client, only need to accept the data sent by the client so response commented out

Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.net.ServerSocket;

Import Java.net.Socket;
 /** * Created by Lpeiz on 2016/9/26. */public class Server {public static void main (string[] args) {try {ServerSocket ServerSocket
= new ServerSocket (12001); 
            System.out.println ("HTTP Server (only POST implemented) is ready and are listening on Port number 12001 \ n"); while (true) {Socket clientsocket = serversocket.accept ();//System.out.print
                ln (clientsocket.getinetaddress (). toString () + "" + Clientsocket.getport ());
BufferedReader in = new BufferedReader (New InputStreamReader (Clientsocket.getinputstream ()));
                OutputStream out = Clientsocket.getoutputstream ();
                String temp;
                int i=1001;
while ((Temp=in.readline ())!= null) System.out.println (temp+i++); String response = "http/1.1 ok\n\r";
Response = response + "Date:fri, May 2001 20:08:11 gmt\n\r";
Response = response + "Server:sanjits server\n\r";
Response = response + "connection:close\n\r";
Response = response + "1";
byte[] bytes = Response.getbytes ();
Byte[]bytes=new byte[1024];
Out.write (bytes);
                Out.flush ();
In.close ();
            Out.close ();
            The catch (Exception e) {System.out.println ("ERROR:" + e.getmessage ());
        System.exit (1);

 }}}

Before the national day to see a case but ran when found to be wrong 13 years ago, now still use this count also really need to learn more advanced technology

Https://coderanch.com/t/205623/java/Java-Http-Server-Java-Http

On the client's program with reference to other successful procedures found on the Internet, and added two lines to find success ...

Con.setreadtimeout (5000)//Set read timeout of 5 seconds
            Con.setconnecttimeout (10000);/Set Connection network timeout of 10 seconds
This is the two lines of control time, and still don't understand why. Might be a refresh problem after the execution of a statement similar to a JDBC connection

public class Client {public static void main (string[] args) {try {URL url = new URL ("Http://loc
            Alhost:12001 ");
            HttpURLConnection con = (httpurlconnection) url.openconnection ();
Con.setdooutput (TRUE);
            Con.setdoinput (TRUE);
Con.setrequestmethod ("POST");
            Con.setusecaches (FALSE); Con.setreadtimeout (5000)//Set read timeout of 5 seconds con.setconnecttimeout (10000);/Set Connection network timeout of 10 seconds String test =
            "<name>Hello</name>";

byte[] bytes = Test.getbytes ();

            Con.setrequestproperty ("Content-type", "text/html");

            OutputStream out = Con.getoutputstream ();
            Out.write (bytes);
            Out.flush ();
            Out.close ();
            BufferedReader in = new BufferedReader (New InputStreamReader (Con.getinputstream ()));
            String temp;
while (temp = In.readline ())!= null) System.out.println (temp); //            Out.close ();
            In.close ();
        Con.disconnect ();
            catch (Exception e) {e.printstacktrace ();
 System.exit (1);}}}





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.