原创

Java 8 with apache httpClient 4 json

发送json

public static String sendJson(String url, String jsonData){
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(url);
//  String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";

    try {
        StringEntity entity = new StringEntity(jsonData);
        httpPost.setEntity(entity);

        // set your POST request headers to accept json contents
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        try {
            // your closeablehttp response
            CloseableHttpResponse response = client.execute(httpPost);

            // print your status code from the response
            System.out.println(response.getStatusLine().getStatusCode());

            // take the response body as a json formatted string
            String responseJSON = EntityUtils.toString(response.getEntity());

            // convert/parse the json formatted string to a json object
            JSONObject jobj = JSONObject.fromObject(responseJSON);

            //print your response body that formatted into json
            System.out.println(jobj);

            return responseJSON;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

接收json

package com.controller;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("test")
public class TestConttroller{

    @Resource
    protected HttpServletRequest request;

    @RequestMapping(value="receivejson",produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.POST)
    public Map<String,Object> getString() throws UnsupportedEncodingException, IOException{
        // 接收
        InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8");
        char [] buff=new char[1024];
        int length=0;
        while((length=reader.read(buff))!=-1){
             String x=new String(buff,0,length);
             // 此处是接收到的json数据
             System.out.println(x);
        }
        // 模拟响应
        Map<String,Object> jsonObject = new HashMap<String, Object>();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "success");
        return jsonObject;
    }
}
正文到此结束
该篇文章的评论功能已被站长关闭
本文目录