Android entry encapsulates a helper class for HTTP requests

               

In the previous article, we have implemented an HTTP GET and POST request;

Here I encapsulate an auxiliary class of HTTP get and post, which can be used better;


Class name: HttpRequestUtil

The following functions are provided:

(1) simulate GET request;

(2) simulate POST request;

(3) upload request of simulation file;

(4) sending XML data;


Send GET request


(1)public static URLConnection sendGetRequest(String url, Map<String, String> params, Map<String, String> headers)

Parameters:

(1)url: a simple URL without any parameters;

(2)params: parameter;

(3)headers: HTTP request headers to be set;

Return:

HttpURLConnection


Send POST request


(2)public static URLConnection sendPostRequest(String url, Map<String, String> params, Map<String, String> headers)

Parameters:

(1)url: a simple URL without any parameters;

(2)params: parameter;

(3)headers: HTTP request headers to be set;

Return:

HttpURLConnection


File upload


(3)public static boolean uploadFiles(String url, Map<String, String> params, FormFile[] files)

Parameters:

(1)url: simple URL

(2)params: parameter;

(3)files: multiple files

Return: upload succeeded

(4)public static boolean uploadFile(String path, Map<String, String> params, FormFile file)

Parameters:

(1)url: simple URL

(2)params: parameter;

(3)file: a file

Return: upload succeeded


Send XML data


(5)public static byte[] postXml(String url, String xml, String encoding)

Parameters:

(1)url: simple URL

(2)xml: XML data

(3)XML data encoding


For upload files, the constructor declaration of FormFile is as follows:

(1)public FormFile(String filname, byte[] data, String parameterName, String contentType)

Parameters:

(1)filname: the name of the file

(2)data: file data

(3)parameterName: the name of the parameter of the HTML file upload control

(4)contentType: file type, for example, text/plain is txt

(2)public FormFile(String filname, File file, String parameterName, String contentType)

Parameters:

(1)filname: the name of the file

(2)file: file name

(3)parameterName: the name of the parameter of the HTML file upload control

(4)contentType: file type, for example, text/plain is txt



FormFile.java


package com.xiazdong.netword.http.util;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;/** * Upload file*/public class FormFile /* Upload file data */ private byte[] data; private InputStream inStream; private File file; /* File name */ private String filname; /* Request parameter name*/ private String parameterName; /* Content type */ private String contentType = "application/octet-stream";  /**  * This function is used to transfer small files* @param filname  * @param data  * @param parameterName  * @param contentType  */ public FormFile(String filname, byte[] data, String parameterName, String contentType) {  this.data = data;  this.filname = filname;  this.parameterName = parameterName;  if(contentType!=null) this.contentType = contentType; } /**  * This function is used to transfer large files* @param filname  * @param file  * @param parameterName  * @param contentType  */ public FormFile(String filname, File file, String parameterName, String contentType) {  this.filname = filname;  this.parameterName = parameterName;  this.file = file;  try {   this.inStream = new FileInputStream(file);  } catch (FileNotFoundException e) {   e.printStackTrace();  }  if(contentType!=null) this.contentType = contentType; }  public File getFile() {  return file; } public InputStream getInStream() {  return inStream; } public byte[] getData() {  return data; } public String getFilname() {  return filname; } public void setFilname(String filname) {  this.filname = filname; } public String getParameterName() {  return parameterName; } public void setParameterName(String parameterName) {  this.parameterName = parameterName; } public String getContentType() {  return contentType; } public void setContentType(String contentType) {  this.contentType = contentType; } }

HttpRequestUtil.java

package com.xiazdong.netword.http.util;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.InetAddress;import java.net.Socket;import java.net.URL;import java.net.URLConnection;import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.Set;/* * This class is used to send HTTP requests* */public class HttpRequestUtil /**  * Send GET request* @param url  * @param params  * @param headers  * @return  * @throws Exception  */ public static URLConnection sendGetRequest(String url,   Map<String, String> params, Map<String, String> headers)   throws Exception {  StringBuilder buf = new StringBuilder(url);  Set<Entry<String, String>> entrys = null;  // If it is a GET request, the request parameter is in the URL  if (params != null && !params.isEmpty()) {   buf.append("?");   entrys = params.entrySet();   for (Map.Entry<String, String> entry : entrys) {    buf.append(entry.getKey()).append("=")      .append(URLEncoder.encode(entry.getValue(), "UTF-8"))      .append("&");   }   buf.deleteCharAt(buf.length() - 1);  }  URL url1 = new URL(buf.toString());  HttpURLConnection conn = (HttpURLConnection) url1.openConnection();  conn.setRequestMethod("GET");  // Set request header  if (headers != null && !headers.isEmpty()) {   entrys = headers.entrySet();   for (Map.Entry<String, String> entry : entrys) {    conn.setRequestProperty(entry.getKey(), entry.getValue());   }  }  conn.getResponseCode();  return conn; } /**  * Send POST request* @param url   * @param params  * @param headers  * @return   * @throws Exception  */ public static URLConnection sendPostRequest(String url,   Map<String, String> params, Map<String, String> headers)   throws Exception {  StringBuilder buf = new StringBuilder();  Set<Entry<String, String>> entrys = null;  // If there are parameters, they are placed in the HTTP request body, such as name = AAA & age = 10  if (params != null && !params.isEmpty()) {   entrys = params.entrySet();   for (Map.Entry<String, String> entry : entrys) {    buf.append(entry.getKey()).append("=")      .append(URLEncoder.encode(entry.getValue(), "UTF-8"))      .append("&");   }   buf.deleteCharAt(buf.length() - 1);  }  URL url1 = new URL(url);  HttpURLConnection conn = (HttpURLConnection) url1.openConnection();  conn.setRequestMethod("POST");  conn.setDoOutput(true);  OutputStream out = conn.getOutputStream();  out.write(buf.toString().getBytes("UTF-8"));  if (headers != null && !headers.isEmpty()) {   entrys = headers.entrySet();   for (Map.Entry<String, String> entry : entrys) {    conn.setRequestProperty(entry.getKey(), entry.getValue());   }  }  conn.getResponseCode(); // In order to send successfully  return conn; } /**  * Submit data to the server directly through HTTP protocol, and realize the following form submission function: * < form method = post action = "http://192.168.0.200:8080 / SSI / fileload / test. Do" enctype = "multipart / form data" > < input type = "text" name = "name" > < input type = "text" name = "Id" > < input type = "file" name = "imagefile" / > < input type = "file" name = "zip" />   </FORM>  * @param path Upload path (Note: avoid path test such as localhost or 127.0.0.1, because it will point to mobile phone simulator, you can use path test such as http://www.itcast.cn or http://192.168.1.10:8080)* @param params The request parameter key is the parameter name and the value is the parameter value* @param file Upload file */ public static boolean uploadFiles(String path, Map<String, String> params, FormFile[] files) throws Exception{             final String BOUNDARY = "---------------------------7da2137580612"; //Data separator        final String endline = "--" + BOUNDARY + "--\r\n";//Data end flag                int fileDataLength = 0;        if(files!=null&&files.length!=0){         for(FormFile uploadFile : files){//Get the total length of file type data          StringBuilder fileExplain = new StringBuilder();           fileExplain.append("--");           fileExplain.append(BOUNDARY);           fileExplain.append("\r\n");           fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");           fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");           fileExplain.append("\r\n");           fileDataLength += fileExplain.length();          if(uploadFile.getInStream()!=null){           fileDataLength += uploadFile.getFile().length();        }else{         fileDataLength += uploadFile.getData().length;        }         }        }        StringBuilder textEntity = new StringBuilder();        if(params!=null&&!params.isEmpty()){         for (Map.Entry<String, String> entry : params.entrySet()) {//Construct entity data for text type parameters             textEntity.append("--");             textEntity.append(BOUNDARY);             textEntity.append("\r\n");             textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");             textEntity.append(entry.getValue());             textEntity.append("\r\n");         }        }        //Calculate the total length of entity data transferred to the server        int dataLength = textEntity.toString().getBytes().length + fileDataLength +  endline.getBytes().length;                URL url = new URL(path);        int port = url.getPort()==-1 ? 80 : url.getPort();        Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);                OutputStream outStream = socket.getOutputStream();        //The following completes the sending of HTTP request header        String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";        outStream.write(requestmethod.getBytes());        String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";        outStream.write(accept.getBytes());        String language = "Accept-Language: zh-CN\r\n";        outStream.write(language.getBytes());        String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";        outStream.write(contenttype.getBytes());        String contentlength = "Content-Length: "+ dataLength + "\r\n";        outStream.write(contentlength.getBytes());        String alive = "Connection: Keep-Alive\r\n";        outStream.write(alive.getBytes());        String host = "Host: "+ url.getHost() +":"+ port +"\r\n";        outStream.write(host.getBytes());        //After writing the HTTP request header, write another carriage return according to the HTTP protocol        outStream.write("\r\n".getBytes());        //Send entity data of all text types        outStream.write(textEntity.toString().getBytes());                //Send entity data of all file types        if(files!=null&&files.length!=0){         for(FormFile uploadFile : files){          StringBuilder fileEntity = new StringBuilder();           fileEntity.append("--");           fileEntity.append(BOUNDARY);           fileEntity.append("\r\n");           fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");           fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");           outStream.write(fileEntity.toString().getBytes());           if(uploadFile.getInStream()!=null){            byte[] buffer = new byte[1024];            int len = 0;            while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){             outStream.write(buffer, 0, len);            }            uploadFile.getInStream().close();           }else{            outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);           }           outStream.write("\r\n".getBytes());         }        }        //Send the data end flag below to indicate that the data has ended        outStream.write(endline.getBytes());        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));        if(reader.readLine().indexOf("200")==-1){//Read the data returned by the web server and judge whether the request code is 200. If it is not 200, it means the request fails         return false;        }        outStream.flush();        outStream.close();        reader.close();        socket.close();        return true; } /**  * Submit data to server* @param path Upload path (Note: avoid path test such as localhost or 127.0.0.1, because it will point to mobile phone simulator, you can use path test such as http://www.itcast.cn or http://192.168.1.10:8080)* @param params The request parameter key is the parameter name and the value is the parameter value* @param file Upload file */ public static boolean uploadFile(String path, Map<String, String> params, FormFile file) throws Exception{    return uploadFiles(path, params, new FormFile[]{file}); } /**  * Flow input to byte array* @param inStream  * @return  * @throws Exception  */ public static byte[] read2Byte(InputStream inStream)throws Exception{  ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  byte[] buffer = new byte[1024];  int len = 0;  while( (len = inStream.read(buffer)) !=-1 ){   outSteam.write(buffer, 0, len);  }  outSteam.close();  inStream.close();  return outSteam.toByteArray(); } /**  * Flow input to string* @param inStream  * @return  * @throws Exception  */ public static String read2String(InputStream inStream)throws Exception{  ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  byte[] buffer = new byte[1024];  int len = 0;  while( (len = inStream.read(buffer)) !=-1 ){   outSteam.write(buffer, 0, len);  }  outSteam.close();  inStream.close();  return new String(outSteam.toByteArray(),"UTF-8"); } /**  * Send xml data* @param path Request address* @param xml xml Data * @param encoding Encoding * @return  * @throws Exception  */ public static byte[] postXml(String path, String xml, String encoding) throws Exception{  byte[] data = xml.getBytes(encoding);  URL url = new URL(path);  HttpURLConnection conn = (HttpURLConnection)url.openConnection();  conn.setRequestMethod("POST");  conn.setDoOutput(true);  conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);  conn.setRequestProperty("Content-Length", String.valueOf(data.length));  conn.setConnectTimeout(5 * 1000);  OutputStream outStream = conn.getOutputStream();  outStream.write(data);  outStream.flush();  outStream.close();  if(conn.getResponseCode()==200){   return read2Byte(conn.getInputStream());  }  return null; } //Test function public static void main(String args[]) throws Exception {  Map<String, String> params = new HashMap<String, String>();  params.put("name", "xiazdong");  params.put("age", "10");  HttpURLConnection conn = (HttpURLConnection) HttpRequestUtil    .sendGetRequest(      "http://192.168.0.103:8080/Server/PrintServlet",      params, null);  int code = conn.getResponseCode();  InputStream in = conn.getInputStream();  byte[]data = read2Byte(in); }}



Test code:

Map<String,String> params = new HashMap<String,String>();params.put("name", name.getText().toString());params.put("age", age.getText().toString());HttpURLConnection conn = (HttpURLConnection) HttpRequestUtil.sendGetRequest("http://192.168.0.103:8080/Server/PrintServlet", params, null);


File upload test code:


FormFile formFile = new FormFile(file.getName(), file, "document", "text/plain");boolean isSuccess = HttpRequestUtil.uploadFile("http://192.168.0.103:8080/Server/FileServlet", null, formFile);


It's a lot easier, isn't it?





           

Keywords: Java xml encoding socket

Added by Hallic7 on Mon, 25 Nov 2019 20:39:29 +0200