本实例采用HttpClient技术,通过Json处理数据,实例代码:
发送方发送并接收数据:
public static JSONObject postHttpClient(String url,JSONObject json) throws Exception{
//创建默认的 HttpClient 实例
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
httpPost.setEntity(s);
System.out.println("execurting request:" + httpPost.getURI());
HttpResponse httpResponse = null;
httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode());
//接收数据
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
String jsonStr = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),charset));
String temp = reader.readLine();
while(temp!=null){
jsonStr+=temp;
temp = reader.readLine();
}
response = JSONObject.fromObject(jsonStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
log.debug(e.getMessage());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
log.debug(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
log.debug(e.getMessage());
} finally {
//关闭连接,释放资源
httpClient.getConnectionManager().shutdown();
}
return response;
}
接收方接收数据并返回:
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuffer sb = new StringBuffer();
String line = null;
List<XxtsDomain> dataList = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null){
sb.append(line);
}
JSONObject jsonObject = JSONObject.fromObject(sb.toString());
JSONArray array = jsonObject.getJSONArray("dataList");
dataList = JSONArray.toList(array, new XxtsDomain(), new JsonConfig());
for (XxtsDomain xxtsDomain: dataList) {
if(postTsxxOne(xxtsDomain)){
xxtsDomain.setSendBool(true);
}else{
xxtsDomain.setSendBool(false);
}
}
} catch (Exception e) {}
// 输出
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
XxtsAllDomain xxtsAll = new XxtsAllDomain();
xxtsAll.setDataList(dataList);
JSONObject jsonList = JSONObject.fromObject(xxtsAll);
out.println(jsonList.toString());
out.flush();
out.close();
}
json 部分可参考另一篇文章