5.post upload and compress, plug-in impersonation request

Source: Internet
Author: User
Tags form post

Gzip

Gzip A compression method, or file form, that is used primarily for the compression of network transmission data

gzip Compression not good
    • Browser: Network speed must be. The smaller the content. Request a response faster
    • Mobile server: The return data type is json/xml-> text-and the compression rate is high.
Gzip Execution Process
    • 1. Inform the server. Client Support gzip Decompression

      * get.addHeader("Accept-Encoding", "gzip");
    • 2. The server knows the gzip compression according to the response header

      * Header[] headers = response.getHeaders("Content-Encoding");    for (Header header : headers) {        if ("gzip".equals(header.getValue())) {            isUseGzip = true;        }}
    • 3. Extract specific data based on whether Gzip is used.

      if (isUseGzip) {    GZIPInputStream in = new GZIPInputStream(entity.getContent());    result = IoUtils.convertStreamToString(in);} else {    result = EntityUtils.toString(entity);}
    • Server-side how to support gzip compression. Depending on the language of the servers used

form of the POST request parameter
    • Key-value---> form: The structure is relatively single. And it's more cumbersome.

      List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();    for (String key : parmas.keySet()) {        BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, parmas.get(key));        parameters.add(basicNameValuePair);    }    UrlEncodedFormEntity form = new UrlEncodedFormEntity(parameters);    post.setEntity(form);
    • Jsonstring form: Flexible structure. A lot of practical development

          post.setEntity(new StringEntity(jsonString));
    • File form: Jar package Required: Many frames upload images using his

          MultipartEntity entity = new MultipartEntity();    entity.addPart("actimg", new FileBody(file));    post.setEntity(entity);
    • Multiple images upload: Write a loop, with the key value, you can use Basicnamevaluepair, you can also use file, loop Add, you can also use Base64 into string upload

    • base64:byte[]-->string
      • upload pictures, Voice:
IV = (ImageView) Findviewbyid (R.ID.IV); Findviewbyid (R.ID.BTN1). Setonclicklistener (New Onclicklistener () {@ overridepublic void OnClick (View v) {//1.bitmapbitmap bitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.ic_launcher);//2. Bitmap-->byte[]bytearrayoutputstream BAOs = new Bytearrayoutputstream (); Bitmap.compress ( Bitmap.CompressFormat.PNG, BAOs); byte[] ByteArray = Baos.tobytearray ();//3.byte[]->string, This allows string to be passed to the server string bitmapstring = Base64.encodetostring (ByteArray, Base64.default); System.out.println ("bitmapstring:" + bitmapstring);//4. string-->byte[];byte[] Bitmapbytearr = Base64.decode (bitmapstring, base64.default);//5.byte[]-->bitmapBitmap BITMAP2 = Bitmapfactory.decodebytearray (Bitmapbytearr, 0, bitmapbytearr.length);//6. Set Picture Iv.setimagebitmap (BITMAP2) on ImageView;//obj-->byte[]-->STRING->SP});

  

Content-type of Post
    • application/x-www-form-urlencoded: Form type-->key-value, default
    • Multipart/form-data: File Upload
    • Application/json:jsonstring
    • Text/xml:xml
    • Text/plain: Text
    • Post.addheader ("Content-type", "Application/json");//If the background is fixed dead. Do not add the request header. It's OK to return the JSON as well. But if the background logic is related to this request header, it must be added. to be sure, that's a foolproof.

Mainactivity

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initgzip (); map<string, string> map = new hashmap<string, string> (); Map.put ("Name", "Billy"); Initpostkeyvalue (map); String jsonstring = "{\" name\ ": \" billy\ "}"; initpostjsonstring (jsonstring); File File = new file (""); Initpostfile (file);} /** * File Upload * @param files */private void initpostfile (file file) {try {defaulthttpclient httpClient = new Defaulthttpclien T (); HttpPost post = new HttpPost ("");//2. Parameters that pass binary type multipartentity entity = new Multipartentity () Entity.addpart ("Actimg", new Filebody (file));p ost.setentity (entity); Httpclient.execute (post);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} /** * Using jsonstring Post database * @param jsonstring */private void initpostjsonstring (String jsonstring) {try {Defaulthttpclien T httpClient = new defaulthttpclient (); HttpPost post = new HtTppost ("");p Ost.addheader ("Content-type", "Application/json");//content-type Text/xml-->xml//content-type APPLICATION/JSON--&GT;JSON//2. Pass the parameter of the jsonstring type post.setentity (new Stringentity (jsonstring)); Httpclient.execute (post);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}  /** * Use key-value form POST data * @param parmas request parameter for the Map collection */private void Initpostkeyvalue (map<string, string> parmas) {try {defaulthttpclient httpClient = new Defaulthttpclient (); HttpPost post = new HttpPost ("");//1. Pass Key-value parameters list<basicnamevaluepair> parameters = new arraylist<basicnamevaluepair> (); for (String key: Parmas.keyset ()) {Basicnamevaluepair Basicnamevaluepair = new Basicnamevaluepair (key, Parmas.get (key)); Parameters.Add (Basicnamevaluepair);} urlencodedformentity form = new Urlencodedformentity (parameters);p ost.setentity (form); Httpclient.execute (post);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} private void Initgzip () {fIndviewbyid (R.ID.BTN1). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {New Thread (new Runnable () {@Overridepublic void run () {try {boolean isusegzip = false;defaulthttpclient httpClient = new Defaulthttpclien T (); HttpGet get = new HttpGet ("Http://httpbin.org/gzip");//1. Inform the server. The client supports gzip decompression Get.addheader ("accept-encoding", "gzip"); HttpResponse response = Httpclient.execute (GET), if (Response.getstatusline (). Getstatuscode () = = 200) {//2. According to the response header, the server knows whether gzip compression header[] headers = response.getheaders ("content-encoding"); for (header Header:headers) {if (" Gzip ". Equals (Header.getvalue ())) {Isusegzip = true;}} httpentity entity = response.getentity ();//3. Based on whether Gzip is used. Extract specific data string result = ""; if (isusegzip) {Gzipinputstream in = NE W Gzipinputstream (Entity.getcontent ()); result = Ioutils.convertstreamtostring (in);} else {result = entityutils.tostring (entity);} SYSTEM.OUT.PRINTLN ("Result:" + result);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace();}}}). Start ();}});}}

  

Restclient (Firfox plugin), postman (Google Chrome)

Network request simulation Plug-in, post, get directly in the browser Web page opened

5.post upload and compress, plug-in impersonation 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.