Android发送post与get请求

Java服务端端代码
新建MyServlet继承HttpServlet处理请求

package com.demo.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServlet
 */
@WebServlet("/MyServlet")//web.xml中不用配置servlet-mapping
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求发送的数据
        String content=request.getQueryString();
        content=URLDecoder.decode(content,"UTF-8");
        System.out.println(content);

        //向客户端返回数据
        OutputStream os=response.getOutputStream();
        String back="你好,我是服务端,收到get请求,正在处理!!!";
        os.write(URLEncoder.encode(back,"UTF-8").getBytes());
        os.flush();
        os.close();

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取post请求发送的数据
        InputStream inputStream=request.getInputStream();
        String content=NetUtils.readString(inputStream);
        content=URLDecoder.decode(content,"UTF-8");
        System.out.println(content);

        //向客户端返回数据
        OutputStream os=response.getOutputStream();
        String back="你好,我是服务端,收到post请求,正在处理!!!";
        os.write(URLEncoder.encode(back,"UTF-8").getBytes());
        os.flush();
        os.close();
    }

}

web.xml配置

 <servlet>
    <servlet-name>MyServletservlet-name>
    <servlet-class>com.demo.util.MyServletservlet-class>
  servlet>

Android端

package com.demo.util;

import android.util.Log;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by xiaowen on 2017/12/30.
 */

public class PostGetUtil {


    /**
     * 使用post方式与服务器通讯
     * @param content
     * @return
     */
    public static String SendPostRequest(String content){
        HttpURLConnection conn=null;
        try {
            String Strurl="http://服务器IP:8080/ServletDemo/ServletDemo";
            URL url = new URL(Strurl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("ser-Agent", "Fiddler");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setConnectTimeout(5 * 1000);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(URLEncoder.encode(content.toString(), "UTF-8").getBytes());
            outputStream.flush();
            outputStream.close();
            if(HttpURLConnection.HTTP_OK==conn.getResponseCode()){
                Log.i("PostGetUtil","post请求成功");
                InputStream in=conn.getInputStream();
                String backcontent=IOUtils.readString(in);
                backcontent= URLDecoder.decode(backcontent,"UTF-8");
                Log.i("PostGetUtil",backcontent);
                in.close();
            }else {
                Log.i("PostGetUtil","post请求失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            conn.disconnect();
        }
        return null;
    }

    /**
     * 使用get方式与服务器通信
     * @param content
     * @return
     */
    public static String SendGetRequest(String content){

        HttpURLConnection conn=null;
        try {

            String Strurl="http://服务器IP:8080/ServletDemo/ServletDemo?"+content;
            URL url = new URL(Strurl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if(HttpURLConnection.HTTP_OK==conn.getResponseCode()){
                Log.i("PostGetUtil","get请求成功");
                InputStream in=conn.getInputStream();
                String backcontent=IOUtils.readString(in);
                backcontent= URLDecoder.decode(backcontent,"UTF-8");
                Log.i("PostGetUtil",backcontent);
                in.close();
            }
            else {
                Log.i("PostGetUtil","get请求失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            conn.disconnect();
        }
        return null;
    }
}

Tomcat报错处理

The servlets named [MyServlet] and [com.demo.util.MyServlet] are both mapped to the url-pattern [MyServlet]

在MyServlet类中:@WebServlet(“/MyServlet”)//在这里自动定义了
所以在web.xml文件中就不需要再重复定义了,将servlet-mapping属性删除即可。

Api
HttpServletRequest接口:

返回类型 方法名 描述
java.lang.String getQueryString() Returns the query string that is contained in the request URL after the path.(返回URL后面的参数)
ServletInputStream getInputStream() Retrieves the body of the request as binary data using a ServletInputStream.(获取客户端发送数据的输入流)


HttpServletResponse接口:

返回类型 方法名 描述
ServletOutputStream getOutputStream() Returns a ServletOutputStream suitable for writing binary data in the response.(获取输出流向客户端发送数据)


类 HttpURLConnection
http://tool.oschina.net/apidocs/apidoc?api=jdk-zh
类URL
http://tool.oschina.net/apidocs/apidoc?api=jdk-zh

你可能感兴趣的:(Android开发学习记录)