android客户端怎么与服务器交互

如题所述

第1个回答  2016-08-13
1、java服务器建立至少一种服务webservices、servlet、socket
2、客户端通过socket或者httpurlconnection的方式进行连接访问
服务端:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");

PrintWriter out = resp.getWriter();
//用HTML格式给浏览器返回数据
out.println("<html>");
out.println("<head>");
out.println("<title>Tomcat Servlet测试</title>");
out.println("</head>");
out.println("<body>");
out.println("Hello,First Servlet!");
out.println("</body>");
out.println("</html>");
out.println("Hello,第一个Tomcat!!!");
out.close();
}
客户端:
private String doGet(String url){
String responseStr = "";
try {
String name = nameEdit.getText().toString().trim();
String code = codeEdit.getText().toString().trim();
String getUrl = URL + "?NAME=" + name+"&"+"CODE=" + code;

HttpGet httpRequest = new HttpGet(getUrl);
HttpParams params = new BasicHttpParams();
ConnManagerParams.setTimeout(params, 1000);
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 5000);
httpRequest.setParams(params);

HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
final int ret = httpResponse.getStatusLine().getStatusCode();
if(ret == HttpStatus.SC_OK){
responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
}else{
responseStr = "-1";
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return responseStr;
}本回答被提问者采纳
相似回答