在Android中提交数据到服务器和平时的浏览器差不多分为三步:
第一步:打开一个浏览器,
第二部:输入一个网址;
第三部:敲回车。
Get实现代码例:
//打开一个浏览器
HttpClient client = new DefaultHttpClient();
String path = "http://192.168.1.100:8080/web/LoginServlet?username=" + username + "&password=" + password;
//输入网址
HttpGet httpGet = new HttpGet(path);
//敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLline().getStatusCode();
if(code == 200){
InputStream is = response.getEntity.getContent();
String text = StreamTools.readInputStream(is);
}
Post实现代码例:
//打开一个浏览器
HttpClient client = new DefaultHtttClient();
//输入网址
String path = "http://192.168.1.100:8080/web/LoginServlet";
HttpPost httpPost = new HttpPost(path);
//指定要提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodeFormEntiry(parameters, "UTF-8"));
//敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();