Httpclient--get,post

Source: Internet
Author: User

Package com.ch.day5_httpclient;

Import java.util.List;

Import Com.ch.myutils.NetWorkUtil;
Import Com.google.gson.Gson;
Import Com.google.gson.reflect.TypeToken;

Import Android.os.Bundle;
Import Android.os.Handler;
Import android.app.Activity;
Import Android.content.Context;
Import android.content.Intent;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;

public class Mainactivity extends Activity {
Private EditText username;
Private EditText Userpass;
Private Button login;
Context Mcontext;

Handler h = new Handler () {
public void Handlemessage (Android.os.Message msg) {
if (msg.what = = 1) {
if (Msg.obj.equals ("Success")) {
Jump
Intent it = new Intent (mcontext,baseactivity.class);
StartActivity (IT);
}else{
Toast.maketext (Mcontext, "POST request, account not correct", 0). Show ();
}
}else if (msg.what = = 2) {
Toast.maketext (Mcontext, (String) msg.obj,0). Show ();
if (Msg.obj.equals ("Success")) {
Jump
Intent it = new Intent (mcontext,baseactivity.class);
StartActivity (IT);
}else{
Toast.maketext (Mcontext, "POST request, account not correct", 0). Show ();
}
}
};
};

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Mcontext = Mainactivity.this;
Init ();
}

public void init () {
Username = (EditText) Findviewbyid (r.id.username);
Userpass = (EditText) Findviewbyid (R.id.userpass);
Login = (Button) Findviewbyid (R.id.login);

Login.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
Get landed Xinix
Final String namevalue = Username.gettext (). toString ();
Final String Passvalue = Userpass.gettext (). toString ();
if (namevalue! = NULL && namevalue! = "" && passvalue! = NULL && Passvalue! = "") {
Determine if the network is open
if (networkutil.isnetavailable (Mcontext)) {//Is true, indicates network is enabled
Get a server request to log in via thread
New Thread () {
public void Run () {
Request Server
String rs =
Networkutil.logincheck_get_httpclient (Namevalue, Passvalue, Networkutil.login_url);
H.sendmessage (H.obtainmessage (1, RS));
String rs =
Networkutil.logincheck_post_httpclient (Namevalue, Passvalue, Networkutil.login_url);
H.sendmessage (H.obtainmessage (2, RS));
};
}.start ();

}

}else{
Toast.maketext (Mcontext, "Please enter the full account information", 0). Show ();
}
}
});
}

}

Package com.ch.myutils;

Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.util.ArrayList;
Import java.util.List;

Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpGet;
Package com.ch.myutils;

Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.util.ArrayList;
Import java.util.List;

Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.message.BasicNameValuePair;
Import Org.apache.http.params.BasicHttpParams;
Import Org.apache.http.params.HttpConnectionParams;
Import Org.apache.http.params.HttpParams;
Import Org.apache.http.util.EntityUtils;

Import Android.content.Context;
Import Android.net.ConnectivityManager;
Import Android.net.NetworkInfo;

public class Networkutil {
public static final String Login_url = "Http://101.200.142.201:8080/tqyb/login";
public static Boolean isnetavailable (context context) {
Get network Manager
Connectivitymanager connm =
(Connectivitymanager) Context.getsystemservice (Context.connectivity_service);
Networkinfo netInfo = Connm.getactivenetworkinfo ();//Get network details

if (NetInfo = = NULL | |!netinfo.isavailable ())
return false;

return true;
}

public static string Logincheck_get_httpclient (string name,string pass,string URL) {
Processing URLs via StringBuffer
StringBuffer sb = new StringBuffer (URL);
Sb.append ("Username=");
Sb.append (name);
Sb.append ("&userpass=");
Sb.append (pass);

String result = "";

HttpGet get = new HttpGet (sb.tostring ());//Create a HttpClient Get Request object
Set Request parameters
Httpparams params = new Basichttpparams ();
Httpconnectionparams.setconnectiontimeout (params, 5*1000);
Httpconnectionparams.setsotimeout (params, 5*1000);

HttpClient client = new Defaulthttpclient (params);//Create HttpClient Object

try {
HttpResponse res = Client.execute (get);//execute request, get results
if (Res.getstatusline (). Getstatuscode () = = 200) {
httpentity entity = res.getentity ();//obtain the corresponding result, is a Httpentity object
result = entityutils.tostring (entity, "utf-8");//Convert to String
}
} catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
return result;

}

public static string Logincheck_post_httpclient (string name,string pass,string URL) {
String result = "";

HttpPost post = new HttpPost (URL);//Create a httpclient Post request object
Set Request parameters
Httpparams params = new Basichttpparams ();
Httpconnectionparams.setconnectiontimeout (params, 5*1000);
Httpconnectionparams.setsotimeout (params, 5*1000);
Pass Value
Create a list collection that holds the data passed to the server
list<namevaluepair> reqdata = new arraylist<namevaluepair> ();
Namevaluepair P1 = new Basicnamevaluepair ("username", name);
Namevaluepair P2 = new Basicnamevaluepair ("Userpass", pass);
Reqdata.add (p1);
Reqdata.add (p2);

try {
httpentity entity = new Urlencodedformentity (reqdata, "utf-8");
Post.setentity (entity);//to the POST request object, set the uploaded data
HttpClient client = new Defaulthttpclient (params);//Create HttpClient Object
HttpResponse res = Client.execute (post);//perform POST request to get results
if (Res.getstatusline (). Getstatuscode () = = 200) {
Httpentity resentity = res.getentity ();//obtain the corresponding result, is a Httpentity object
result = Entityutils.tostring (resentity, "utf-8");//Convert to String
}
} catch (Unsupportedencodingexception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
} catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

return result;

}


}

Httpclient--get,post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.