Java's put request for HTTP

Source: Internet
Author: User
Emphasis in this sentence: Httpurlconnection.setrequestmethod ("put");
If you want to change to a POST request, it should be Httpurlconnection.setrequestmethod ("POST");


public static string Httpput (string URLPath, String data, String CharSet, string[] header) {string result = NULL;
		URL url = null;
		HttpURLConnection httpurlconnection = null;
			try {url = new URL (urlpath);
			HttpURLConnection = (httpurlconnection) url.openconnection ();
			Httpurlconnection.setdoinput (TRUE);
			Httpurlconnection.setdooutput (TRUE); Httpurlconnection.setconnecttimeout (2000000)//Set the connection host timeout (in milliseconds) httpurlconnection.setreadtimeout (2000000);  Set timeout for reading data from host (in milliseconds) if (header!= null) {for (int i = 0; i < header.length; i++) {string[] Content
					= Header[i].split (":");
				Httpurlconnection.setrequestproperty (Content[0], content[1]);
			} httpurlconnection.setrequestmethod ("put");

			Httpurlconnection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
			if (Stringutils.isnotblank (data)) {Httpurlconnection.getoutputstream (). Write (Data.getbytes ("UTF-8")); } httpurlconnection.getoutputstream (). Flush ();
			Httpurlconnection.getoutputstream (). Close ();

			int code = Httpurlconnection.getresponsecode ();
				if (code = =) {DataInputStream in = new DataInputStream (Httpurlconnection.getinputstream ());
				int len = in.available ();
				Byte[] by = new Byte[len];
				In.readfully (by);
				if (Stringutils.isnotblank (CharSet)) {result = new String (by, Charset.forname (CharSet));
				else {result = new String (by);
			} in.close ();
			else {Log.error ("request Address: + URLPath +" returns the state exception, the exception number is: "+ code);
		The catch (Exception e) {log.error ("Access URL address:" + URLPath + "exception", e);
			finally {URL = null;
			if (httpurlconnection!= null) {httpurlconnection.disconnect ();
	} return 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.