用httpPost对JSON发送和接收的例子
HTTPPost发送JSON:
private static final String APPLICATION_JSON = "application/json"; private static final String CONTENT_TYPE_TEXT_JSON = "text/json"; public static void httpPostWithJSON(String url, String json) throws Exception { // 将JSON进行UTF-8编码,以便传输中文 String encoderJson = URLEncoder.encode(json, HTTP.UTF_8); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON); StringEntity se = new StringEntity(encoderJson); se.setContentType(CONTENT_TYPE_TEXT_JSON); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON)); httpPost.setEntity(se); httpClient.execute(httpPost); }
接收HTTPPost中的JSON:
public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException { // 读取请求内容 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(); return URLDecoder.decode(reqBody, HTTP.UTF_8); }
以下为自己开发实例:
接收HTTPPost中的JSON,并且通过Gson解析:
import com.google.gson.Gson; public AttendanceInfo getAttendanceInfoFromBbchat(){ // 读取请求内容 ToftContext context = ToftContext.getToftContext(); try { InputStream in = context.getRequest().getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = br.readLine()) != null) { stringBuffer.append(str); } String info = stringBuffer.toString(); if(StringUtils.isNotBlank(info)){ Gson gson = new Gson(); AttendanceInfo attendanceInfo = gson.fromJson(info, AttendanceInfo.class); if(StringUtils.isNotBlank(attendanceInfo.getToken())){ context.getRequest().setAttribute("token", attendanceInfo.getToken()); } return attendanceInfo; } }catch (Exception e) { // TODO: handle exception log.error("bbchat 解析邦邦社区考勤json参数出现异常"); e.printStackTrace(); } return null; }
HTTPPost发送JSON:
public static String pushAttendanceInfo(){ String url = "http://ibb.anbanggroup.com:8080/push/push"; HttpClient httpClient = new HttpClient(); // 设置连接超时时间(单位毫秒) httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60*1000); // 设置读取超时时间(单位毫秒) httpClient.getHttpConnectionManager().getParams().setSoTimeout(60*1000); PostMethod method = new PostMethod(url); String info = null; try { String aaa = "{\"token\": \"ee32da94162d4b688af2b0241db4600a\",\"touser\":\"AB044979\""+ ",\"msgtype\":\"text\",\"msg\":{\"content\": \"Hello\"},\"start\":\"\",\"end\":\"2015-05-30 00:00:00\"}"; RequestEntity entity = new StringRequestEntity(aaa, "application/json", "UTF-8"); method.setRequestEntity(entity); httpClient.executeMethod(method); int code = method.getStatusCode(); if (code == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = reader.readLine()) != null) { stringBuffer.append(str); } info = stringBuffer.toString(); log.info("bbchat 返回报文:"+info); }else{ log.error("bbchat 接口返回失败 httpStatusCode="+code); } } catch (Exception ex) { ToftLogger.error("内部接口报文发送异常:" + ex.getMessage()); ex.printStackTrace(); } finally { if (method != null) { method.releaseConnection(); } } return info; }
HTTPPost发送参数:
/** * 考勤推送接口登陆 * @return */ public static String loginAttendancePush(){ String url = "http://ibb.anbanggroup.com:8080/authenticate/ablogin"; HttpClient httpClient = new HttpClient(); // 设置连接超时时间(单位毫秒) httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60*1000); // 设置读取超时时间(单位毫秒) httpClient.getHttpConnectionManager().getParams().setSoTimeout(60*1000); PostMethod method = new PostMethod(url); String info = null; try { method.setParameter("username", "27607"); method.setParameter("password", "cd55abee1c0ef6d4525a223faf00c96a193576f58ceb39b9"); httpClient.executeMethod(method); int code = method.getStatusCode(); if (code == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = reader.readLine()) != null) { stringBuffer.append(str); } info = stringBuffer.toString(); log.info("bbchat 返回报文:"+info); }else{ log.error("bbchat 接口返回失败 httpStatusCode="+code); } } catch (Exception ex) { ToftLogger.error("内部接口报文发送异常:" + ex.getMessage()); ex.printStackTrace(); } finally { if (method != null) { method.releaseConnection(); } } return info; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。