After a few days of tossing, the HTTP is finally settled. After testing, it is normal, but it is used for preliminary test cases, because we need to modify it later to save the current version to the blog.
Among them, POST requires two package files to be imported because it involves multipart upload. I used the latest httpmine4.3 and found that many articles related to MultipartEntity on the Internet are early versions. Some previous methods are still available, however, it is not recommended in the new version, so all of them are processed using the new MultipartEntityBuilder method.
httpmime-4.3.2.jar httpcore-4.3.1.jar
Android studio may encounter a problem: Android Duplicate files copied in APK
POST Processing is normal after testing, and no garbled characters are found.
The complete code is as follows:
ZHttpRequest. java
Package com. ai9475.util; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. httpStatus; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpPost; import org. apache. http. client. methods. httpRequestBase; import org. apache. http. entity. contentType; import org. apache. http. entity. mime. httpMultipartMode; import org. apache. http. entity. mime. multipartEntityBuilder; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. params. basicHttpParams; import org. apache. http. params. httpConnectionParams; import org. apache. http. params. httpParams; import org. apache. http. protocol. HTTP; import java. io. byteArrayOutputStream; import java. io. file; import java. io. IOException; import java. io. inputStream; import java. io. unsupportedEncodingException; import java. nio. charset. charset; import java. util. iterator; import java. util. map; import java. util. set;/*** Created by ZHOUZ on 14-2-3. */public class ZHttpRequest {protected String url =; protected Map
Headers = null; protected int connectionTimeout = 5000; protected int soTimeout = 10000; protected int statusCode = 200; protected String charset = HTTP. UTF_8; protected HttpGet httpGet; protected HttpPost; protected HttpParams httpParameters; protected HttpResponse httpResponse; protected HttpClient httpClient; protected String inputContent; /*** set the link of the current request ** @ param url * @ return */pub Lic ZHttpRequest setUrl (String url) {this. url = url; return this;}/*** Set Request header Information ** @ param headers * @ return */public ZHttpRequest setHeaders (Map headers) {this. headers = headers; return this;}/*** set the connection timeout time ** @ param timeout (MS). The default value is 5000 * @ return */public ZHttpRequest setConnectionTimeout (int timeout) {this. connectionTimeout = timeout; return this;}/*** set the socket read timeout * * @ Param timeout unit (millisecond), default 10000 * @ return */public ZHttpRequest setSoTimeout (int timeout) {this. soTimeout = timeout; return this;}/*** set the encoding format for the retrieved content ** @ param charset the default is UTF-8 * @ return */public ZHttpRequest setCharset (String charset) {this. charset = charset; return this;}/*** get http Request Response Information ** @ return */public HttpResponse getHttpResponse () {return this. httpResponse;}/*** GET HTTP Client Connection Manager ** @ return */public HttpClient getHttpClient () {return this. httpClient;}/*** GET Request status code ** @ return */public int getStatusCode () {return this. statusCode;}/*** request data through GET ** @ param url * @ return * @ throws IOException */public String get (String url) throws IOException {// set the current request link this. setUrl (url); // instantiate GET connection this. httpGet = new HttpGet (this. url); // custom configuration header information this. AddHeaders (this. httpGet); // initialize the client request this. initHttpClient (); // send the HTTP request this. httpResponse = this.httpClient.exe cute (this. httpGet); // read remote data this. getInputStream (); // whether the remote Request status code is normal if (this. statusCode! = HttpStatus. SC _ OK) {return null;} // return all read strings return this. inputContent;} public String post (String url, Map
Datas, Map
Files) throws IOException {this. setUrl (url); // instantiate GET connection this. httpPost = new HttpPost (this. url); // custom configuration header information this. addHeaders (this. httpPost); // initialize the client request this. initHttpClient (); Iterator iterator = datas. entrySet (). iterator (); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder. create (); multipartEntityBuilder. setMode (HttpMultipartMode. BROWSER_COMPATIBLE); multipartEntityBuilder. setCharset (Charset. forName (this. charset); // The sent data while (iterator. hasNext () {Map. entry
Entry = (Map. Entry
) Iterator. next (); multipartEntityBuilder. addTextBody (entry. getKey (), entry. getValue (), ContentType. create (text/plain, Charset. forName (this. charset);} // sent file if (files! = Null) {iterator = files. entrySet (). iterator (); while (iterator. hasNext () {Map. Entry
Entry = (Map. Entry
) Iterator. next (); String path = entry. getValue (); if (. equals (path) | path = null) continue; File file = new File (entry. getValue (); multipartEntityBuilder. addBinaryBody (entry. getKey (), file) ;}// generate the HTTP entity HttpEntity httpEntity = multipartEntityBuilder. build (); // set the object part of the POST request this. httpPost. setEntity (httpEntity); // send the HTTP request this. httpResponse = this.httpClient.exe cute (this. httpPost );/ /Read remote data this. getInputStream (); // whether the remote Request status code is normal if (this. statusCode! = HttpStatus. SC _ OK) {return null;} // return all strings read return this. inputContent. toString ();}/*** add header information for the HTTP request ** @ param request */protected void addHeaders (HttpRequestBase request) {if (this. headers! = Null) {Set keys = this. headers. entrySet (); Iterator iterator = keys. iterator (); Map. Entry
Entry; while (iterator. hasNext () {entry = (Map. Entry
) Iterator. next (); request. addHeader (entry. getKey (). toString (), entry. getValue (). toString () ;}}/ *** configure Request Parameters */protected void setParams () {this. httpParameters = new BasicHttpParams (); this. httpParameters. setParameter (charset, this. charset); // set the connection request timeout value HttpConnectionParams. setConnectionTimeout (this. httpParameters, this. connectionTimeout); // sets the socket read timeout value. setSoTimeo Ut (this. httpParameters, this. soTimeout);}/*** initialize and configure the client request */protected void initHttpClient () {// configure the HTTP request parameter this. setParams (); // enable a client HTTP request this. httpClient = new DefaultHttpClient (this. httpParameters);}/*** read Remote Data ** @ throws IOException */protected void getInputStream () throws IOException {// receive remote input stream InputStream inStream = this. httpResponse. getEntity (). getContent (); // reads input stream data in segments TeArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buf = new byte [1024]; int len =-1; while (len = inStream. read (buf ))! =-1) {baos. write (buf, 0, len);} // convert the data into a string and save this. inputContent = new String (baos. toByteArray (); // exit inStream after data is received. close (); // get the status code returned by the request this. statusCode = this. httpResponse. getStatusLine (). getStatusCode ();}/*** close Connection Manager to release resources */protected void shutdownHttpClient () {if (this. httpClient! = Null & this. httpClient. getConnectionManager ()! = Null) {this. httpClient. getConnectionManager (). shutdown ();}}}
MainActivity. java
I will write only the event part.
Public void doClick (View view) {ZHttpRequest request = new ZHttpRequest (); String url =; TextView textView = (TextView) findViewById (R. id. showContent); String content = empty content; try {if (view. getId () = R. id. doGet) {url = http://www.baidu.com; content = GET data: + request. get (url);} else {url = http: // 192.168.1.6/test. php; HashMap
Datas = new HashMap
(); Datas. put (p1, abc); datas. put (p2, Chinese); datas. put (p3, abc Chinese CBA); datas. put (pic, this. picPath); HashMap
Files = new HashMap
(); Files. put (file, this. picPath); content = POST data: + request. post (url, datas, files) ;}} catch (IOException e) {content = IO exception: + e. getMessage ();} catch (Exception e) {content = Exception: + e. getMessage ();} textView. setText (content );}
Here, this. picPath is the String type of the photo path in the specified SD card.
Activity_main.xml
Because I am not very familiar with Java now, I only read some video tutorials and have little practical development experience. I write comments based on my own understanding, but there should be no major problems, if any error occurs, please point it out. Thank you!