The most important access to the network is the http protocol.
The http protocol is simple, but it's important.
Directly on the code, which is a code block code block, with which part of the direct copy to use.
1. Access the network and submit parameters by get and post, httpclient
2. Upload and download
3. For example, simple parsing methods of xml and json returned after visiting the server
String path = "http://192.168.13.1"; String username ="ll"; String pwd="123"; /** get Group competition */ public void httpGet() throws Exception { String param1 = URLEncoder.encode(username); String param2 = URLEncoder.encode(pwd); URL url = new URL(path + "?name=" + param1 + "&password=" + param2); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); // Data not sent to server // Get the flow information returned by the server InputStream in = conn.getInputStream(); byte[] result = StreamTool.getBytes(in); //return new String(result); } /** post Group competition */ public void httpPost() throws Exception { URL url = new URL(path); String param1 = URLEncoder.encode(username); String param2 = URLEncoder.encode(pwd); //Start connecting HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String data = "username=" + param1 + "&password=" + param2; //Set mode post conn.setRequestMethod("POST"); //timeout 5000 conn.setConnectTimeout(5000); // Set http protocol to write data to server conn.setDoOutput(true); // Set message header of http protocol conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length())); // Write the prepared data to the server OutputStream os = conn.getOutputStream(); os.write(data.getBytes()); // The underlying implementation of httpurlconnection: outputstream is a buffered output stream // As long as we get the information returned by any server, the data will be submitted to the server to get the flow information returned by the server int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); byte[] result = StreamTool.getBytes(is); String ss= new String(result); } } /** httpclient get */ public void httpClentGet () throws Exception{ //Get an instance of a browser HttpClient client = new DefaultHttpClient(); //Address to prepare the request String param1 = URLEncoder.encode(username); String param2 = URLEncoder.encode(pwd); HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2); //Knock back request HttpResponse ressponse = client.execute(httpGet); int code = ressponse.getStatusLine().getStatusCode(); if( code == 200){ InputStream is =ressponse.getEntity().getContent(); //byte[] result = StreamTool.getBytes(is); } } // Close httpclient. Getconnectionmanager(). Shutdown(), when not needed; /** httpclient post **/ public void httpClentPost() throws Exception{ //1. Get an instance of a browser HttpClient client = new DefaultHttpClient(); HttpPost httppost = new HttpPost(path); // Key value pair BasicNameValuePair List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("username", username)); parameters.add(new BasicNameValuePair("pwd", pwd)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); //3. Set the data entity of post request httppost.setEntity(entity); //4. Send data to server HttpResponse ressponse = client.execute(httppost); int code = ressponse.getStatusLine().getStatusCode(); if(code == 200){ InputStream is =ressponse.getEntity().getContent(); byte[] result = StreamTool.getBytes(is); //return new String(result); } } /*** Download a thing***/ public void getFileData(Context context){ try { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(path); //implement HttpResponse ressponse = client.execute(httpGet); int code = ressponse.getStatusLine().getStatusCode(); if(code == HttpStatus.SC_OK){ InputStream in =ressponse.getEntity().getContent(); //picture // Bitmap bitmap = BitmapFactory.decodeStream(in); // in.close(); //For example, if you read a file, you need to write it locally. //Small files directly read large files read a little bit and write a little bit //byte[] result = StreamTool.getBytes(in); // //Here you can get the type of file, such as image/jpg /zip /tiff, but it is not very effective. Sometimes it is clear that the suffix is. rar, but it is null. This is especially important. System.out.println(ressponse.getEntity().getContentType()); //Can determine whether it is a file data flow System.out.println(ressponse.getEntity().isStreaming()); //Set up locally saved files //File storeFile = new File("c:/0431la.zip"); String path="sdcard/aa.txt"; FileOutputStream output = context.openFileOutput(path, context.MODE_PRIVATE); //Get network resources and write files InputStream input = ressponse.getEntity().getContent(); byte b[] = new byte[1024]; int j = 0; while( (j = input.read(b))!=-1){ output.write(b,0,j); } output.flush(); output.close(); } } catch (Exception e) { // TODO: handle exception } } /** * Submit data to server with a file * @param filepath The path of the file on the phone */ public void PostData(String filepath) throws Exception{ // Instantiate the array part [] username PWD of uploaded data Part[] parts = { new StringPart("username", username), new StringPart("pwd", pwd), new FilePart("file", new File(filepath)) }; PostMethod file_Post = new PostMethod(path); // Multiple types of data entities file_Post.setRequestEntity(new MultipartRequestEntity(parts, file_Post.getParams())); //Create client org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); //timeout client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //implement int status = client.executeMethod(file_Post); if(status==200){ } } //transfer file public void setFile() throws Exception{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.1"); File file = new File(path); InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // FileEntity entity = new FileEntity(file, "binary/octet-stream"); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); if(response.getStatusLine().getStatusCode() == 200){ } } /** 1. * Generally, a web service will be returned after visiting * pull Parsing and accessing the xml returned from webservice * **/ public void pullJX(byte[] bb) throws Exception{ // byte[] bb = EntityUtils.toByteArray(response.getEntity()); XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(new ByteArrayInputStream(bb), "UTF-8"); int event = pullParser.getEventType(); List<Object> info; while(event != XmlPullParser.END_DOCUMENT){ switch (event) { case XmlPullParser.START_DOCUMENT: info = new ArrayList<Object>(); break; case XmlPullParser.START_TAG: if("aa".equals(pullParser.getName())){ String id = pullParser.nextText().toString(); } break; case XmlPullParser.END_TAG: if("aa".equals(pullParser.getName())){ } break; } event = pullParser.next(); } } /**2. * Parse json data [{id:"001",name:"lilei",age:"20"},{id:"002",name:"zhangjia",age:"30"}] */ private static List parseJSON(InputStream in) throws Exception{ byte[] data = StreamTool.getBytes(in); String s =new String(data); // Convert to json array object [{"001","ll","20"},{"002","zj","30"},] JSONArray json = new JSONArray(s); for (int i = 0; i < json.length() ; i++) { JSONObject j = json.getJSONObject(i); String aa1 = j.getString("id"); String aa2 = j.getString("name"); String aa3 = j.getString("age"); } return null; }
HttpClient is actually an interface type. HttpClient encapsulates the Http request, authentication, connection management and other features that an object needs to perform.
HttpClient has three known implementation classes:
AbstractHttpClient, AndroidHttpClient, DefaultHttpClient
Android HttpClient is a package of HttpClient, which has access connector inside and can be used by multiple threads.
public class MyApplication extends Application{ private AndroidHttpClient httpClient; // Create when application oncreate public void onCreate(){ super.onCreate(); httpClient = AndroidHttpClient.newInstance("Android"); } //For external calls public AndroidHttpClient getHttpClient() { if (httpClient == null){ httpClient = AndroidHttpClient.newInstance("Android"); } return httpClient; } @Override public void onLowMemory() { super.onLowMemory(); shutdownHttpClient(); } @Override public void onTerminate() { super.onTerminate(); shutdownHttpClient(); } //Close private void shutdownHttpClient() { if (httpClient != null) { if (httpClient.getConnectionManager() != null) { httpClient.getConnectionManager().shutdown(); } httpClient.close(); httpClient = null; } } }
External call
AndroidHttpClient httpClient = ((MyApplication)getApplication()).getHttpClient();
Reproduced at: https://www.cnblogs.com/riasky/p/3464808.html