httpclient post发送json数组并解决json乱码问题

业务:
客户端发送json数据,服务端进行解析

client发送json格式:
{"data":[{"name":"1;,a","id_no":"222,a","cellphone":"123141a","abode_detail":"213,a","emp_add":"werew3a","app_no":"111111111111a","create_time":"11a"},{"name":"张三","id_no":"null","cellphone":"null","abode_detail":"null","emp_add":"null","app_no":"null","create_time":"null"},{"name":"1;,","id_no":"222,","cellphone":"123141","abode_detail":"213,","emp_add":"werew3","app_no":"111111111111","create_time":"11"},{"name":"1;,ab","id_no":"222,ab","cellphone":"123141ab","abode_detail":"213,ab","emp_add":"werew3ab","app_no":"111111111111ab","create_time":"11ab"}],"sendtime":"20160503"}

废话少说,直接上主要代码
client端

package msxf.until;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import msxf.until.model.People;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

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

/**
 * Created by 小省.
 */
public class Main {
    private final static org.apache.log4j.Logger logger =org.apache.log4j.Logger.getLogger(Main.class);
    public static void main(String[] args) {
        Map ma=new HashMap();
        ma.put("sendtime","20160503");
        //连接impala查库,返回List,其中peopel为自定义实体类
        List peopleList=ImpalaJdbc.connImpala();
        if(peopleList.size()==0){
            logger.info("peopleList.size()==0");
        }
        ma.put("data",peopleList);
        ObjectMapper om=new ObjectMapper();
        try {
            String jsonStr=om.writeValueAsString(ma);
            System.out.println(jsonStr);

            CloseableHttpResponse httpResponse=null;
            CloseableHttpClient httpClient= HttpClientBuilder.create().setRetryHandler(new DefaultHttpRequestRetryHandler()).build();

            //解决中文乱码,注意与服务端同时存在
            StringEntity stringEntity=new StringEntity(jsonStr,"UTF-8");
        //就目前来说下面这段代码是可有可无  stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        //post 地址
            HttpUriRequest httpUriRequest= RequestBuilder.post("http://localhost:8080/qc").setEntity(stringEntity).build();
        httpResponse=httpClient.execute(httpUriRequest);
            System.out.println("发送");
            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if(statusCode== HttpStatus.SC_OK){
//              HttpEntity entity = httpResponse.getEntity();
//              InputStream in =entity.getContent();
                System.out.println("文件传输服务器正常响应!");
            }

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务端
采用最原始的servlet

import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;

/**
 * Created by 小省.
 */
public class QcServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
System.out.println("+++++++++++++++++++");
//解决中文乱码
BufferedReader br =new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String line=null;
StringBuffer sb =new StringBuffer();
while ((line=br.readLine())!=null){
sb.append(line);
}
System.out.println("sb.toString()"+sb.toString());
//就目前而言String reesult = URLDecoder.decode(sb.toString(), HTTP.UTF_8);是可有可无的,httpclient会自动解码
//String reesult =sb.toString();
String reesult = URLDecoder.decode(sb.toString(), HTTP.UTF_8);
try {
//将string 字符串转化为json数组,并且遍历
JSONObject jsonObject =new JSONObject(reesult);


String mesage=(String) jsonObject.getString("data");
JSONArray myJsonArray = new JSONArray(mesage);
for(int i=0 ; i < myJsonArray.length() ;i++){
//获取每一个JsonObject对象
JSONObject myjObject = myJsonArray.getJSONObject(i);
System.out.println(myjObject.getString("name"));
}
System.out.println(reesult);


} catch (JSONException e) {
e.printStackTrace();
}

}
}

你可能感兴趣的:(工作之行)