客户端到服务器的post请求

本文详细介绍了客户端如何通过HTTP Post方式与服务器进行交互的过程,包括客户端的连接初始化、请求发送及响应处理,以及服务器端如何解析请求并返回JSON格式的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:客户端

A:连接方法

    public String getDateFromService(Context context,List<NameValuePair> userpair,String filter){
        String postStr = Common.HTTPSTR + filter;
        String result = null;
        InputStream is = null;
        try {
            // TODO Auto-generated method stub
            HttpPost httpPost = new HttpPost(postStr);
            httpPost.setEntity(new UrlEncodedFormEntity(userpair, HTTP.UTF_8));
            
            HttpResponse response = HTTPCLIENT.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            result = Common.ConvertStreamToString(is);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                is = null;
            }
        }
        return result;
    }
B:初始化http连接
    public static void initHttp(){
        HTTPPARAMS = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(HTTPPARAMS, TIMEOUT);
        HTTPCLIENT = new DefaultHttpClient(HTTPPARAMS);
    }
C:在Application onCreate的时候调用Common的initHttp()方法

D:在需要调用post的地方调用common的getDateFromService,参数是Context,NameValuePair,filter(filter是URl的一部分,如果不需要就可以不用)

String filter = "getarea";
                Common com = new Common();
                List<NameValuePair> domainpairs = new ArrayList<NameValuePair>();
                domainpairs.add(new BasicNameValuePair("domain", "SPINNER"));
                String result = null;
                do {
                    result = com.getDateFromService(ShopListActivity.this,domainpairs, filter);
                } while(result == null);

E:将inputStream转换成String

    public static String ConvertStreamToString(InputStream is){
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String returnStr = "";
        try {
            while ((returnStr = br.readLine()) != null) {
                sb.append(returnStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        final String result = sb.toString();
        return result;
    }


F:将返回的result转换成对应的对象数据(List)

JSONArray.parseArray(result,
                            SpinnerArea.class);
G:将返回的数据转换成对应的对象数据

JSON.parseObject(result, ShopInfo.class);
2:服务器端

A:post处理

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		String shoptype=req.getParameter("shoptype");
pw.println(result);}
B:返回json,将对象数据转换成json

result = JSON.toJSON(shoplist).toString();

result = JSON.toJSON(shopinfo).toString();

完成

            //建立连接
            httpparams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpparams, timeout);
            httpclient = new DefaultHttpClient(httpparams);
            //发送请求
            HttpPost hp = new HttpPost(httpstr);
            List<NameValuePair> pair = new ArrayList<NameValuePair>();
            pair.add(new BasicNameValuePair("1", "1"));
            hp.setEntity(new UrlEncodedFormEntity(pair,HTTP.UTF_8));
            
            //接收回应
            HttpResponse hps = httpclient.execute(hp);
            HttpEntity he = hps.getEntity();
            is = he.getContent();
            //将InputStream转换成String
            
            StringBuffer sb = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            
            while((resultsa = br.readLine()) != null){
                sb.append(resultsa);
            }
            result = sb.toString();
            //返回Result
            return result;








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值