Android development want to interface to get data is necessary operation, generally get the data has post and got two ways, this article explains the client uses the Post method to use ASP.net webapi to develop interface data.
1. Access Interface class
Package http;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.net.URLEncoder;
Import Android.widget.Toast;
public class Httputils {
public static string Getjsoncontent (string urlpath,string data) {
String webserviceurl= "http://hayi.8888.com";
try {
URL url = new URL (webserviceurl+urlpath);
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
Connection.setconnecttimeout (3000);
Connection.setrequestmethod ("POST");
Connection.setdooutput (TRUE); Send POST request must set allow output
Connection.setdoinput (TRUE);
Get output stream
OutputStream OS = Connection.getoutputstream ();
Os.write (Data.getbytes ());
Os.flush ();
int code = Connection.getresponsecode ();
if (code = = 200) {
Return Changeinputstream (Connection.getinputstream ());
}
catch (Exception e) {
System.out.println (E.getmessage ());
}
Return "";
}
private static String Changeinputstream (InputStream inputstream) {
TODO auto-generated Method Stub
String jsonstring = "";
Bytearrayoutputstream outputstream = new Bytearrayoutputstream ();
int len = 0;
byte[] data = new byte[1024];
try {
while (len = inputstream.read (data))!=-1) {
Outputstream.write (data, 0, Len);
}
jsonstring = new String (Outputstream.tobytearray ());
catch (IOException e) {
E.printstacktrace ();
}
return jsonstring;
}
}
2, the use of methods
//-Passed data
String datapare = "Username=" + Urlencoder.encode (Usernametxt.gettext (). toString (). Trim (), "UTF-8"
& nbsp; + "&userpass=" + Urlencoder.encode (Userpasstxt.gettext (). toString (). Trim (), "UTF-8");
jsonstring = Httputils
getjsoncontent ("/api/values/postuserlogin", datapare);