Java Analog HTTP request submission pictures and data

Source: Internet
Author: User

1, forged request

Package com.sxb.web.v2.wh.unittest;


Import Java.io.BufferedReader;

Import Java.io.DataInputStream;

Import Java.io.DataOutputStream;

Import Java.io.File;

Import Java.io.FileInputStream;

Import java.io.FileNotFoundException;

Import Java.io.InputStream;

Import Java.io.InputStreamReader;

Import Java.io.OutputStream;

Import java.net.HttpURLConnection;

Import Java.net.URL;

Import Java.util.HashMap;

Import Java.util.Iterator;

Import Java.util.Map;




Import Net.sf.jmimemagic.Magic;

Import Net.sf.jmimemagic.MagicMatch;

public class Httppostuploadutil {

/**

* @param args

* @throws FileNotFoundException

*/

public static void Main (string[] args) throws FileNotFoundException {

String filepath = "C:\\users\\administrator\\desktop\\xx.png";

String urlstr = "Http://192.168.0.98:8086/app/wh/test/image.json";

map<string, string> textmap = new hashmap<string, string> ();

Textmap.put ("Name1", "testname1");

map<string, inputstream> filemap = new hashmap<string, inputstream> ();

Filemap.put ("UserFile", New FileInputStream (New File (filepath)));

String ret = httppostuploadutil.formupload (Urlstr, Textmap, Filemap);

SYSTEM.OUT.PRINTLN (ret);

}

/**

* Upload Images

* @param urlstr

* @param textmap

* @param filemap

* @return

*/

public static string Formupload (String urlstr, map<string, string> Textmap, map<string, inputstream> Filemap ) {

String res = "";

HttpURLConnection conn = null;

String boundary = "---------------------------123821742118716"; Boundary is the delimiter for the request header and the content of the uploaded file

try {

URL url = new URL (urlstr);

conn = (httpurlconnection) url.openconnection ();

Conn.setconnecttimeout (5000);

Conn.setreadtimeout (30000);

Conn.setdooutput (TRUE);

Conn.setdoinput (TRUE);

Conn.setusecaches (FALSE);

Conn.setrequestmethod ("POST");

Conn.setrequestproperty ("Connection", "keep-alive");

Conn.setrequestproperty ("User-agent", "mozilla/5.0" (Windows; U Windows NT 6.1; ZH-CN; rv:1.9.2.6) ");

Conn.setrequestproperty ("Content-type", "multipart/form-data; boundary= "+ boundary);

OutputStream out = new DataOutputStream (Conn.getoutputstream ());

Text

if (textmap! = null) {

StringBuffer strbuf = new StringBuffer ();

Iterator<map.entry<string, string>> iter = Textmap.entryset (). Iterator ();

while (Iter.hasnext ()) {

map.entry<string, string> Entry = Iter.next ();

String inputname = (string) entry.getkey ();

String inputvalue = (string) entry.getvalue ();

if (Inputvalue = = null) {

Continue

}

Strbuf.append ("\ r \ n"). Append ("--"). Append (Boundary). Append ("\ r \ n");

Strbuf.append ("Content-disposition:form-data; Name=\ "" + InputName + "\" \r\n\r\n ");

Strbuf.append (Inputvalue);

}

Out.write (Strbuf.tostring (). GetBytes ());

}

File

if (filemap! = null) {

Iterator<map.entry<string, inputstream>> iter = Filemap.entryset (). Iterator ();

while (Iter.hasnext ()) {

map.entry<string, inputstream> Entry = Iter.next ();

String inputname = (string) entry.getkey ();

FileInputStream Inputvalue = (fileinputstream) entry.getvalue ();

if (Inputvalue = = null) {

Continue

}

String filename = system.currenttimemillis () + ". png";

String ContentType = "Image/png";

StringBuffer strbuf = new StringBuffer ();

Strbuf.append ("\ r \ n"). Append ("--"). Append (Boundary). Append ("\ r \ n");

Strbuf.append ("Content-disposition:form-data; Name=\ "" + InputName + "\"; Filename=\ "+ filename +" \ "\ \ \ \ \ \ \");

Strbuf.append ("Content-type:" + contentType + "\r\n\r\n");

Out.write (Strbuf.tostring (). GetBytes ());

DataInputStream in = new DataInputStream (inputvalue);

int bytes = 0;

byte[] Bufferout = new byte[1024];

while ((bytes = In.read (bufferout))! =-1) {

Out.write (bufferout, 0, bytes);

}

In.close ();

}

}

Byte[] Enddata = ("\r\n--" + boundary + "--\r\n"). GetBytes ();

Out.write (Enddata);

Out.flush ();

Out.close ();

Read return Data

StringBuffer strbuf = new StringBuffer ();

BufferedReader reader = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));

String line = null;

while (line = Reader.readline ()) = null) {

Strbuf.append (line) append ("\ n");

}

res = strbuf.tostring ();

Reader.close ();

reader = null;

} catch (Exception e) {

SYSTEM.OUT.PRINTLN ("Error sending post request.") "+ urlstr);

E.printstacktrace ();

} finally {

IF (conn! = null) {

Conn.disconnect ();

conn = null;

}

}

return res;

}

}



2, receiving the data of the forged request

@Controller

@RequestMapping ("/wh/test")

public class TestController {


/**

*

*

* ***/

@RequestMapping ("/image")

public void image (HttpServletRequest request,httpservletresponse response, @RequestParam (value= "UserFile", Required=false) commonsmultipartfile[] images) throws ioexception{

map<string, object> retmp = null;

try {

System.out.println ("--images:" +images[0].getinputstream ());

} catch (Exception e) {

retmp = Retutil.getretvalue (False, "{}", "Server Exception", 500);

e.printstacktrace ();

}finally{

Response.setcontenttype ("Application/json; Charset=utf-8 ");

response.getwriter (). Print (New Gson (). ToJson ("--xx-:" +images[0].getinputstream (). toString ()));

}

}

}


Java Analog HTTP request submission pictures and data

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.