使用Tomcat服务器,具体配置web可参考:Eclipse创建JAVA web工程
创建完成后编写Servlet,代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String host = request.getHeader("Host"); //根据头名称的到头的内容
System.out.println(host);
//遍历所有请求头
Enumeration enums = request.getHeaderNames(); //得到所有的请求头名称列表
while(enums.hasMoreElements()){//判断是否有下一个元素
String headerName = enums.nextElement(); //取出下一个元素
String headerValue = request.getHeader(headerName);
System.out.println(headerName+":"+headerValue);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
InputStream in = request.getInputStream(); //得到实体内容
byte[] buf = new byte[1024];
int len = 0;
while( (len=in.read(buf))!=-1 ){
String str = new String(buf,0,len);
System.out.println(str);
}
response.getWriter().append("post请求成功");
}
}
其中web.xm如下:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>test4display-name>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
<servlet>
<description>description>
<display-name>TestServletdisplay-name>
<servlet-name>TestServletservlet-name>
<servlet-class>test.TestServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>TestServletservlet-name>
<url-pattern>/testurl-pattern>
servlet-mapping>
web-app>
使用AndroidStudio访问本地的URL为:
http://10.0.2.2:8080/test4/test
其中10.0.2.2是本机地址,8080是tomcat服务器监听的端口,test4是工程名字,test是servlet的访问名称,test4/test组成URI。
客户端代码为:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection client = null;
try {
byte[] data = new String("name=JACK&age=27").getBytes("UTF-8");
URL url = new URL("http://10.0.2.2:8080/test4/test");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setConnectTimeout(1500);
client.setReadTimeout(1500);
client.setDoOutput(true);
client.setDoInput(true);
OutputStream out = client.getOutputStream();
out.write(data);
out.flush();
out.close();
//当调用getInputStream方法时才真正将请求体数据上传至服务器
InputStream is = client.getInputStream();
//打印响应状态码,200表明请求成功
Log.d("TAG",client.getResponseCode()+"");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(client!=null){
client.disconnect();
}
}
}
}).start();
}
});
}
}
服务器打印的信息为:
提价json数据:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection client = null;
try {
Map map = new HashMap();
map.put("1","ABC");
map.put("2","DEF");
Gson gson = new Gson();
//导入GSON开源库,构造Gson对象,使用Gson对象的toJson方法将map转化为json格式
String str = gson.toJson(map);
URL url = new URL("http://10.0.2.2:8080/test4/test");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setConnectTimeout(1500);
client.setReadTimeout(1500);
client.setDoOutput(true);
client.setDoInput(true);
OutputStream out = client.getOutputStream();
out.write(str.getBytes());
out.flush();
out.close();
InputStream in = client.getInputStream();
Log.d("TAG",client.getResponseCode()+"");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(client!=null){
client.disconnect();
}
}
}
}).start();
}
});
}
}