package com.spring.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.net.URLDecoder; public class HttpRequestUtils {
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); //日志记录 /**
* httpPost
* @param url 路径
* @param jsonParam 参数
* @return
*/
public static Object httpPost(String url,JSONObject jsonParam){
return httpPost(url, jsonParam, false);
} /**
* post请求
* @param url url地址
* @param jsonParam 参数
* @param noNeedResponse 不需要返回结果
* @return
*/
public static Object httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
//post请求返回结果
HttpClient httpClient = new DefaultHttpClient();
Object jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
String strResult = "";
try {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
return null;
}
if(strResult.startsWith("[") && strResult.endsWith("]")){
/**把json字符串转换成json对象数组**/
jsonResult = JSONArray.fromObject(strResult); // 首先把字符串转成 JSONArray 对象
}else if(strResult.startsWith("{") && strResult.endsWith("}"))
{
/**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(strResult);
}else
{
return strResult;
}
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
}
return jsonResult;
} /**
* 发送get请求
* @param url 路径
* @return
*/
public static Object httpGet(String url){
//get请求返回结果
Object jsonResult = null;
String strResult = null;
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request); /**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity());
/**把json字符串转换成json对象**/
//接收{}对象,此处接收数组对象会有异常
if(strResult.startsWith("[") && strResult.endsWith("]")){
jsonResult = JSONArray.fromObject(strResult); // 首先把字符串转成 JSONArray 对象
}else if(strResult.startsWith("{") && strResult.endsWith("}"))
{
jsonResult = JSONObject.fromObject(strResult);
}else
{
return strResult;
}
url = URLDecoder.decode(url, "UTF-8");
} else {
logger.error("get请求提交失败:" + url);
}
}catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
}
return jsonResult;
} }

  

基于HttpClient JSONObject与JSONArray的使用的更多相关文章

  1. 基于HttpClient的新版正方教务系统模拟登录及信息获取API

    简介 通过HttpClient获取网页数据源,通过Jsoup解析数据.先模拟登录,再获取信息.模拟浏览器正常操作,封装请求头信息获取SESSIONID.模拟登录成功后切勿断开会话,依赖登录请求得到的C ...

  2. json学习系列(6)JSONObject和JSONArray是JDK的集合部分延伸

    我一直觉得JSONObject和JSONArray是JDK集合部分的延伸,它们与JDK的List和Map一脉相承.通过研究JSONObject和JSONArray的结构,我们顺便也复习一下JDK的内容 ...

  3. JSONObject与JSONArray的使用

    1.JAR包简介 要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包: commons-lang.jar commons-beanutils.jar commons ...

  4. Java学习笔记50:JSONObject与JSONArray的使用

    Java不像PHP解析和生产JSON总是一个比较痛苦的过程.但是使用JSONObject和JSONArray会让整个过程相对舒服一些. 需要依赖的包:commons-lang.jar commons- ...

  5. Gson解析JsonObject和JsonArray

    Gson中重要的几个核心类: Gson.JsonParser.JsonObject.JsonArray. 下面就是解析的步骤: public void parserJsonArray(String s ...

  6. JSONObject和JSONArray

    点击下载json工具 点击下载支持jar包 1.从Object到String 要先用Object对象构造一个JSONObject或者JSONArray对象,然后调用它的toString()方法即可 ( ...

  7. [转]JSONObject与JSONArray的使用

    http://www.cnblogs.com/xwdreamer/archive/2011/12/16/2296904.html 参考文献: http://blog.csdn.net/huangwuy ...

  8. json:JSONObject与JSONArray的使用

    1.JAR包简介 要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包: commons-lang.jar commons-beanutils.jar commons ...

  9. JSONObject和JSONArray区别及基本用法

    一.JSONObject和JSONArray的数据表示形式 JSONObject的数据是用 {  } 来表示的, 例如:   { "id" : "123", & ...

随机推荐

  1. 数据集 过滤时 RecordCount 属性

    如果是在 OnFilterRecord里写代码,过滤后RecordCount 是不变的. 如果是用 Filter属性过滤,过滤后RecordCount 是变的=过滤后的记录数. 难怪 有的说 变的,有 ...

  2. 《Python》 while循环、运算符和编码初识

    一.while 循环 while也叫无限循环 while 条件: 循环体 判断条件: 条件为真,进入循环体,循环体执行到底部,返回,继续判断条件. 终止循环: 1.改变条件(标志位的概念) 2.bre ...

  3. hibernate缓存清除(转)

    文章有点杂,这不是原文,谢谢贡献者 http://www.360doc.com/content/16/0413/16/32415095_550307388.shtml 一.hibernate一级缓存( ...

  4. input 文件上传

    <button class="blueButton fileinput-button" style="width:165px;" @click=" ...

  5. Spring Cloud Sleuth进阶实战

    转载请标明出处: http://blog.csdn.net/forezp/article/details/76795269 本文出自方志朋的博客 为什么需要Spring Cloud Sleuth 微服 ...

  6. windows运行打开服务命令

    1. gpedit.msc-----组策略    2. sndrec32-------录音机   3. Nslookup-------IP地址侦测器   4. explorer-------打开资源管 ...

  7. javascript 处理鼠标右键事件

    使用右键事件 在需要右键的地方加上  onmousedown="if(event.button == 2) alert('点击右键了!');即可   不经意地被一位同事问起在javascri ...

  8. 负margin

    负margin理论: 何谓参考线?参考线就是 margin移动的基准点,此基准点相对于box(自身)是静止的.而margin的数值,就是box相对于参考线的位移量. 一个完整的margin属性是这么写 ...

  9. 【opencv基础】detectMultiScale-output detection score

    前言 使用FDDB数据库评估人脸检测的效果时,需要计算人脸区域的得分,具体问题请参考FDDB-FAQ. 实现过程 根据here和here的描述,可以使用cascade.detectMultiScale ...

  10. 【计算机视觉】交并比IOU概念理解

    前言 交并比IOU(Intersection over Union)是一种测量在特定数据集中检测相应物体准确度的一个标准. 图示 很简单,IoU相当于两个区域重叠的部分除以两个区域的集合部分得出的结果 ...