HttpClient发送JSON数据

本文介绍了一个简单的HTTP客户端和服务端交互示例,包括如何使用HttpClient发送POST请求及服务端如何接收请求并返回响应数据。

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

1、客服端的HttpClient发送POST请求:
`

//发送JSON数据
public void httpSend(String url){
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost httpPost = new HttpPost(Constant.LOGINURI);
        List<NameValuePair> nameValuePair = new ArrayList<>();
        JSONObject jsonData = new JSONObject();//发送数据
        JSONObject jsonObject = new JSONObject();//存放发送数据的JSON数据
        jsonData.put("loginResult", loginResult);
        jsonData.put("loginMode",loginMode);
        jsonData.put("username",userName);
        jsonData.put("password",password);
        jsonObject.put("userMsg", jsonData);            

        nameValuePair.add(new BasicNameValuePair("jsStr", jsonObject.toString()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"utf-8"));
        //httpClient 响应,接收数据
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // 如果响应成功
        if( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            StringBuilder builder = new StringBuilder();
            br = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
            for(String s=br.readLine();s!=null;s=br.readLine()){
                builder.append(s);
            }
            //转换JSON数据 
            JSONObject jsonRespnse = new JSONObject(builder.toString()).getJSONObject("userMsg");
            httpResult = jsonRespnse.getString("loginResult");
        }
        br.close();

    } catch (Exception e) {

    }
}


2、服务端接受手机并发送响应数据:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //接收数据
    request.setCharacterEncoding("UTF-8");
    jsStr = request.getParameter("jsStr");

    JSONObject jsO = new JSONObject(jsStr).getJSONObject("userMsg");//获取用户的JSON数据
    loginMode = jsO.getString("loginMode");
    username = jsO.getString("username");
    password = jsO.getString("password");

    //响应数据
    response.setContentType("application/json;charset=UTF-8");  
    response.setCharacterEncoding("UTF-8");  
    response.setHeader("Cache-Control", "no-cache");  
    String json = "{\"userMsg\":{\"username\" : "+username+" , \"loginResult\":"+loginResult+"}}" ;  
    ServletOutputStream out = response.getOutputStream();
    out.write(json.getBytes());
    out.close();


}

`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值