In Android Network Development, HTTP requests are often used. To avoid code duplication, we must learn to encapsulate an HTTP request class.
Method 1:
public class Network {public String makeHttpRequest(String url, List<NameValuePair> params) {try{ .............}catch (JSONException e) { e.printStackTrace(); } }}
First, create an http post online in the makehttpresquest method.
DefaultHttpClient httpClient = new DefaultHttpClient();
A new httppost object
HttpPost httpPost = new HttpPost(url);
Set the encoding format for the request
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
Execute request
HttpResponse httpResponse = httpClient.execute(httpPost);HttpEntity httpEntity = httpResponse.getEntity();is = httpEntity.getContent();
Use bufferedreader to obtain the input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuilder sb = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) { sb.append(line + "\n"); }is.close();
return line;
Of course, various exceptions need to be caught in the middle. Finally, when we need to use it, we can just generate one instance.
Network net=new Network();net.makeHttpRequest(url_up,params);
Method 2:
Only requests the URL. This instance is used when I use Dom to parse XML files:
public String getXmlFromUrl(String url) { String xml = null; try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity,"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return XML return xml; }
Different from method 1, entityutils is used here to directly obtain httpentity.