Java socket impersonate the HTTP protocol client POST request

Source: Internet
Author: User
Tags webp

Compared to a GET request, the post message has the following elements:

1,content-length, this is the length of the paper, in bytes.

2,content-type, this is mainly related to the format and character set of the message.

3, is the main message

Main class Simplehttppost:

package com.zws.http;import java.io.ioexception;import java.io.inputstream;import  java.io.outputstream;import java.net.inetsocketaddress;import java.net.socket;import  Java.net.socketaddress;import java.util.hashmap;import java.util.iterator;import java.util.map ;/** *  *  @author  wensh.zhu 2017-03-11   Request message format: Get /greeting.do? name=jack http/1.1\r\nhost: localhost:8011\r\nconnection: keep-alive\r\ncache-control:  max-age=0\r\nupgrade-insecure-requests: 1\r\nuser-agent: mozilla/5.0  (Windows NT 10.0 ;  wow64)  AppleWebKit/537.36  (Khtml, like gecko)  chrome/56.0.2924.87 safari/ 537.36\r\naccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,* here is a slash (/) *;q=0.8\r\ Naccept-encoding: gzip, deflate, sdch, br\r\naccept-language: zh-cn,zh;q=0.8\r\ ncontent-length: 14\r\ncontent-type, application/x-www-form-urlencoded;charset=utf-8\r\n\r\nid=1&name=jack      Response message Format:   disposable response:  http/1.1 200 ok\r\nserver: apache-coyote/1.1\r\nset-cookie:  jsessionid=54b11be01cd7983726618546cf4521e1; path=/newer/; httponly\r\ncontent-type: text /html;charset=utf-8\r\ncontent-length: 4\r\n//message body Length date: sat, 11 mar 2017  15:16:10 gmt\r\n\r\n//header End abcd//body        Chunk response: http/1.1 200 ok\r\ ncontent-type: application/json;charset=utf-8\r\ntransfer-encoding: chunked\r\n//represents chunked response date:  sat, 11 mar 2017 14:19:25 gmt\r\n\r\n     //Header End 8\r\n// Hex length abcdefgh\r\n//body  2\r\nab\r\n0\r\n//End  */public class simplehttppost {private  int connecttimeout = 2000;//Link Timeout Time private int readtimeout = 5000;// Read timeout time private string host;private int port = 80;private string resource =  "/";p rivate string  reqline;private string body;private map<string, string> headers =  new HashMap<String, String> ();p ublic simplehttppost (String uri)  { Initrequestheader ();p arserequestline (URI);} Public simplehttppost (string uri, int connecttimeout, int readtimeout)  { Initrequestheader ();p arserequestline (URI); this.connecttimeout = connecttimeout;this.readtimeout  = readtimeout;} /** *  resolves the IP address, port, and request Resources  *  @param  uri */private void parserequestline ( String uri)  {String url = uri;if  (url == null)  throw new  nullpointerexception ("Uri can not be null");if  (!url.startswith ("http")) URL  =  "/http"  + uri; String[] parts = url.split("//");if  (parts.length >= 2)  {String mainPart = parts[1];int  Ipflag = mainpart.indexof ("/");if  (ipflag != -1)  {string ippart =  mainpart.substring (0, ipflag); resource = mainpart.substring (IpFlag); String[] ipparts = ippart.split (":");if  (ipparts.length > 1)  {host  = ipparts[0]; string portstr = ipparts[1];if  (portstr != null &&  Portstr.length ()  > 0) port = integer.parseint (PORTSTR);}  else {host = ippart;}}  else {host = mainpart;}}  else {throw new illegalargumentexception ("illegal uri");} string hostval = host;if  (port != 80)  hostVal +=  ":"  +  Port;headers.put ("Host",  hostval);reqline =  "post "  + resource +  "  http/1.1\r\n ";} /** *  initialization of the request header  */private void initrequestheader ()  {headers.put ("Connection",  "Keep-alive"); Headers.put ("Upgrade-insecure-requests",  "1"); Headers.put ("User-agent",  "Java  Client "), Headers.put (" Accept ", " text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q= 0.8 "), Headers.put (" accept-encoding ", " gzip "), Headers.put (" Accept-language ", " Zh-cn,zh "); Headers.put ( "Content-type",  "Application/x-www-form-urlencoded;charset=utf-8");} Public void setheader (String key, string value)  {headers.put (key, value);} Private void concatparam (map<string, string> parameters) {if  (parameters ==  null | |  parameters.isempty ())  return; string params =  ""; Iterator<string> itor = parameters.keyset (). Iterator (); while  (Itor.hasnext ())  {string key = itor.next (); String val = pArameters.get (Key);p arams +=  ("&"  + key +  "="  + val);} Body = params.replacefirst ("&",  ");} Public respmsg req (map<string, string> parameters)  {concatparam (parameters); int  contentLen = 0;if  (Body != null) contentlen = body.getbytes (). length; This.headers.put ("Content-length",  string.valueof (Contentlen)); respmsg msg = null; socket socket = null;outputstream out = null;inputstream in =  Null;try {socketaddress endpoint = new inetsocketaddress (host, port); socket  = new socket (); Socket.connect (endpoint, connecttimeout); Socket.setsotimeout (ReadTimeout) ; Out = socket.getoutputstream (); write (out); In = socket.getinputstream ();msg =  Read (in);  catch  (exception e)  {e.printstacktrace ();}  finally {try {if  (Out != null) out.close ();if  (in != null) in.close ();if  (socket  != null)  socket.close ();}  catch  (Exception e2)  {e2.printstacktrace ();}} Return msg;} Private void write (outputstream out)  throws ioexception {string reqbody  = reqline;iterator<string> itor = headers.keyset (). Iterator ();while  ( Itor.hasnext ())  {string key = itor.next (); String val = headers.get (key); string header = key +  ":"  + val +  "\ r \ n";reqbody +=  Header;} reqbody +=  "\ r \ n"; Reqbody += body;out.write (Reqbody.getbytes ("UTF-8"));} Private respmsg read (inputstream in)  throws ioexception {respmsg respmsg  = new respmsg (); Byte[] heads = httpstreamreader.readheaders (in); String headstr = new sTring (heads); String[] lines = headstr.split ("\ r \ n"); Respheader resp = new respheader ();if  (lines.length > 0)   Resp.setrespline (Lines[0]);for  (int i = 1; i < lines.length; i++)  resp.addheader (Lines[i]); string body = null;if  (resp.ischunked ())  {body = readchunked (in);  else {int bodylen = resp.getcontentlenth ();byte[] bodybts = new  Byte[bodylen];in.read (BODYBTS); Body = new string (bodybts,  "UTF-8");} Respmsg.setrespbody (body); String respline = resp.getrespline (); respmsg.setrespcodemsg (respline); return respMsg;} /** *  chunked Read  *  @param  in *  @return  *  @throws  IOException  */private static string readchunked (inputstream in)  throws ioexception { string content =  ""; string lenstr =  "0";while  (!) ( Lenstr = new string (Httpstreamreader.readline (in))). Equals ("0"))  {int len =  integer.valueof (Lenstr.touppercase (), 16);//length 16 binary means byte[] cnt = new byte[len]; In.read (CNT); Content += new string (cnt,  "UTF-8"); In.skip (2);} Return content;}}

Test class Example:

Package Com.zws.http;import Java.util.hashmap;import Java.util.map;public class Example {public static void main (String [] args) {post ();} public static void Post () {String uri = "Http://localhost:8080/Newer/server.action"; map<string, string> params = new hashmap<string, string> ();p arams.put ("id", "123");p arams.put ("name", "Zhang San" ); Simplehttppost post = new Simplehttppost (URI); Respmsg msg = post.req (params); String respcodemsg = msg.getrespcodemsg (); String respbody = Msg.getrespbody (); System.out.println (RESPCODEMSG); System.out.println (Respbody);}}


This article is from the "Evan" blog, be sure to keep this source http://wenshengzhu.blog.51cto.com/5151285/1905644

Java socket impersonate the HTTP protocol client POST request

Related Article

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.