Java okhttp send a POST request

Source: Internet
Author: User

Java's httpclient and okhttp request network, are more troublesome than the requests of PY, also more than the self-brought package of Py urllib trouble. Now think of requests is really for humans, take to use, basic no special case without two times package.

Java or to be encapsulated into a get post tool class is useful, the tool class is a static method of the class, more general, no need to new object. As with the @staticmethod method of py.

 Packagecom.touna.httprequest;ImportJava.util.HashMap;ImportJava.util.Set;ImportOKHTTP3. Formbody;ImportOKHTTP3. okhttpclient;ImportOKHTTP3. Request;ImportOKHTTP3. Requestbody;ImportOKHTTP3. Response; Public classHttputil { Public Static voidPost (string URL, hashmap<string, String >Paramsmap) {//There is no return, you can return string okhttpclient mokhttpclient=Newokhttpclient (); Formbody.builder Formbodybuilder=NewFormbody.builder (); Set<String> KeySet =Paramsmap.keyset ();  for(String key:keyset) {String value=Paramsmap.get (key);        Formbodybuilder.add (Key,value); } formbody formbody=Formbodybuilder.build (); Request Request=NewRequest.        Builder (). Post (formbody). URL (URL). build (); Try(Response Response =Mokhttpclient.newcall (Request). Execute ())        {System.out.println (Response.body (). String ()); }Catch(Exception e) {e.printstacktrace (); }    }     Public Static voidMain (string[] args) {HashMap<String,String> Paramsmap =NewHashmap<string, string>() ; Paramsmap.put ("Name", "Xiaoming"); Paramsmap.put ("HTML", "&LT;HTML&GT; ..."); Post ("HTTPS://10.0.4.147:8015/CRCC", Paramsmap); }}

Java okhttp send a POST request

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.