1, HttpClient method for get submission data
1. Get httpclient instance
DefaultHttpClient client = new DefaultHttpClient();
2. Prepare get request and define an httpget implementation
HttpGet get = new HttpGet(path);
3. Execute a get request
HttpResponse response = client.execute(get);
4. Get the status code returned by the server
int code = response.getStatusLine().getStatusCode();
5. Get the data returned by the server in the form of stream
if(code == 200){ InputStream inputStream = response.getEntity().getContent(); }
6. Convert stream to string
String content = StreamTools.readStream(inputStream);
7. Display results
runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this,content,Toast.LENGTH_SHORT).show(); } });
II. post data submission by HttpClient
Different from the second and third steps of get method, the body submitted by post method should be prepared, and the parameters used should be prepared in turn
2. Prepare the post request and define an httpget implementation
HttpGet post = new HttpGet(path);
3. Prepare the body submitted by post in entity form (key value pair form)
//Prepare parameters List<NameValuePair> lists = new ArrayList<NameValuePair>(); //To prepare NameValuePair is to submit the user name and password. The key is the server key: username, password BasicNameValuePair nameValuePair = new BasicNameValuePair("username",name); BasicNameValuePair pwdValuePair = new BasicNameValuePair("password",pwd); //Add nameValuePair and pwdValuePair to the collection lists.add(nameValuePair); lists.add(pwdValuePair); //Preparing for entity UrlEncodedFormEntity entity = new UrlEncodedFormEntity(lists); //Prepare post submit body prepare as entity (key value pair) post.setEntity(entity);
4. Execute a post request
HttpResponse response = client.execute(post);
3, Open source project way to submit data to the server (asyncHttpClient)
1. Create AsyncHttpClient
AsyncHttpClient client = new AsyncHttpClient();
2. Make a get request
client.get(path,new AsyncHttpResponseHandler(){ //Request success callback method @Override public void onSuccess(int statusCode,Headers,byte[] responseBody){ Toast.makeText(getApplicationContext(),new String(responseBody,"gbk"),Toast.LENGTH_SHORT).show(); } //request was aborted @Override public void onFailure(int statusCode,Header[] headers,byte[] responseBody,Throwable error){ } });
3. post request
RequestParams params = new RequesParams(); params.put("username",name); params.put("password",pwd); client.post(path,params,new AsyncHttpResponseHandler(){ //Request success callback method is not login success @Override public void onSuccess(int statusCode,Headers,byte[] responseBody){ Toast.makeText(getApplicationContext(),new String(responseBody,"gbk"),Toast.LENGTH_SHORT).show(); } //request was aborted @Override public void onFailure(int statusCode,Header[] headers,byte[] responseBody,Throwable error){ } });