码迷,mamicode.com
首页 > 其他好文 > 详细

向服务器端发送数据 Get

时间:2017-12-29 17:24:25      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:red   div   ted   class   cat   protect   prot   服务器   warnings   

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
     * * 向服务器端发送数据
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String urlGetMethod(String url, String params) throws Exception {
        HttpClient httpClient;
        GetMethod method = null;
        String responses;
        if (params != null) {
            // TODO 待调查
            if (url.indexOf("?") < 0) {
                url = url + "?";
            } else {
                url = url + "&";
            }
            url = url + URLEncoder.encode(params, "UTF-8");
        }
        try {
            httpClient = new HttpClient();
            method = new GetMethod(url);
            httpClient.executeMethod(method);
            responses = method.getResponseBodyAsString();//服务器返回内容,若服务器接收后没有返回内容为null
        } catch (Exception e) {
            throw e;
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        return responses;
    }

模拟服务端获取数据

@SuppressWarnings("serial")
public class Export extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
         // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }

        String reqBody = sb.toString();
        System.out.println(reqBody);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

向服务器端发送数据 Get

标签:red   div   ted   class   cat   protect   prot   服务器   warnings   

原文地址:https://www.cnblogs.com/god-monk/p/8145430.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!