android客户端如何与后台java服务器交互
展开全部
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;
}
详细的参见:http://blog.csdn.net/yanzi1225627/article/details/24882569
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询