post提交json

package post;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class PostHttp {

private static final String APPLICATION_JSON = "application/json";

private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DefaultHttpClient httpClient = new DefaultHttpClient();
String url = "http://localhost:8080/test/dischoose/save.jspx";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
String encoderJson = "jsonString";
encoderJson = URLEncoder.encode(encoderJson, HTTP.UTF_8);
StringEntity se = new StringEntity(encoderJson);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
httpPost.setEntity(se);
//返回服务器响应
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); // 服务器返回状态
Header[] headers = response.getAllHeaders(); // 返回的HTTP头信息
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
String responseString = null;
if (response.getEntity() != null) {
responseString = EntityUtils.toString(response.getEntity()); // 返回服务器响应的HTML代码
System.out.println(responseString); // 打印出服务器响应的HTML代码
}
} finally {
if (entity != null)
entity.consumeContent(); // release connection gracefully
}
return;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值