HttpURLConnection的post请求上传键值对和json数据

使用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<String> 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如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>test4</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>test.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <!--servlet的访问名称:/名称-->
    <url-pattern>/test</url-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<String,String> map = new HashMap<String,String>();
                            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();
            }
        });
    }
}

服务器打印结果为:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值