Can anyone explain me this code?

前端 未结 2 1160
后悔当初
后悔当初 2021-01-06 21:02
import org.apache.http.message.BasicNameValuePair;

private String getServerData(String returnString) {               
InputStream is = null;

String result = \"\";
         


        
2条回答
  •  执笔经年
    2021-01-06 21:20

    BasicNameValuePair is an object, specifically a container to holds data and keys.

    For example if you have this data:

    Name: Bob
    
    Family name: Smith
    
    Date of birth: 10/03/1977
    

    then you would store this data as:

    ArrayList nameValuePairs = new ArrayList();
    
    nameValuePairs.add(new BasicNameValuePair("name","bob"));
    
    nameValuePairs.add(new BasicNameValuePair("family name","Smith"));
    
    ....
    

    As you see you choose a key ("name") and data to be stored as linked to the key ("bob"). It's a type of data structure used to speed up and make easier to store this kind of informations.

    On the other end you need a tool to use this data:

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    

    this code can be divided in 4 parts:

    httppost.setEntity
    

    Is a method that take an url as argument, and tries to retrieve data (HTML or what is stored on that page) from that url, using the HTTP Post method.

    new UrlEncodedFormEntity

    Is a method that trasform key-data value pair in something intelligible by an http server.

    it use the convention

    &key=input
    

    which one of the most used, but remember that there more ways to do it.

    nameValuePair
    

    is the data you stored before. In this case it has key the possible input forms in the html, identified by the "input name=" tag. As data it has the value that you want to give to the forms.

    is = entity.getContent();
    

    HttpEntity is an abstraction to help you handle the possible result. If the web site is unreachable or the connection is down, HttpEntity will inform you. getContent() is the method you use the retrieve the body of the Http result, i.e.: the html that the webserver sent you back, as a inputstream. If the request wasn't succesfull it will give you a null value.

    BasicNameValuePair accept only couplets, so you'll have to cast it multiple times and everytime add it to the arraylist.

    You can't cast it to more than two values, as they would be meaningless for the (key, value) representation of data.

    Hope it helped.

提交回复
热议问题