您的位置:首页 > 理论基础 > 计算机网络

http发送json格式数据请求 demo示例

2016-08-04 13:52 579 查看
http发送json格式数据请求 demo示例 

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
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 java.io.IOException;
import java.nio.charset.Charset;

/**
* Created by admin on 2016/8/3.
*/
public class JsonHttpClient {
// 接口地址
private static String apiURL = "http://localhost:8080/...";
private HttpClient httpClient = null;
private HttpPost method = null;
private long startTime = 0L;
private long endTime = 0L;
private int status = 0;

/**
* 接口地址
*
* @param url
*/
public JsonHttpClient(String url) {

if (url != null) {
this.apiURL = url;
}
if (apiURL != null) {
httpClient = new DefaultHttpClient();
method = new HttpPost(apiURL);

}
}

/**
* 调用 API
*
* @param parameters
* @return
*/
public String post(String parameters) {
String body = null;
if (method != null & parameters != null
&& !"".equals(parameters.trim())) {
try {

// 建立一个NameValuePair数组,用于存储欲传送的参数
method.addHeader("Content-type","application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
startTime = System.currentTimeMillis();

HttpResponse response = httpClient.execute(method);

endTime = System.currentTimeMillis();
int statusCode = response.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {
status = 1;
}
// Read the response body
body = EntityUtils.toString(response.getEntity());

} catch (IOException e) {
// 网络错误
status = 3;
}

}
return body;
}

public static void main(String[] args) {
JsonHttpClient ac = new JsonHttpClient(apiURL);
//创建参数列表
JsonArray array = new JsonArray();
JsonObject object = new JsonObject();
object.addProperty("aa","123");
object.addProperty("bb","218");

array.add(object);
JsonObject object1 = new JsonObject();
object1.addProperty("aa","456");
object1.addProperty("bb","2.2");

array.add(object1);

JsonObject res = new JsonObject();
res.addProperty("list",array.toString());
res.addProperty("mm","mmVal");
System.out.println(ac.post(res.toString()));
}

/**
* 0.成功 1.执行方法失败 2.协议错误 3.网络错误
*
* @return the status
*/
public int getStatus() {
return status;
}

/**
* @param status
* the status to set
*/
public void setStatus(int status) {
this.status = status;
}

/**
* @return the startTime
*/
public long getStartTime() {
return startTime;
}

/**
* @return the endTime
*/
public long getEndTime() {
return endTime;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐