(发送http的post请求,xml格式数据)
client 客户端 -------------------------》server服务端,server服务端解析xml返回xml格式的数据响应给client客户端,然后客户端还能根据上一次响应接着发送http请求给服务端吗??(如果可以请付上详细的方法,谢谢大牛们!!)
http的post请求能进行多次数据交换吗?
答案:2 悬赏:60 手机版
解决时间 2021-01-22 23:49
- 提问者网友:爱了却不能说
- 2021-01-22 11:43
最佳答案
- 五星知识达人网友:胯下狙击手
- 2021-01-22 13:21
从数据角度,是一回合。
~~~~~~~~
~~~~~~~~
全部回答
- 1楼网友:迷人又混蛋
- 2021-01-22 14:26
有时候我们在发送http请求的时候会使用到post方式,如果是传送普通的表单数据那将很方便,直接将参数到一个key-value形式的map
中即可。但是如果我们需要传送的参数是json格式的,会稍微有点麻烦,我们可以使用httpclient类库提供的功能来实现这个需求。假设我们需要发
送的数据是:
{
"blog": "",
"author": "iteblog"
}
我们可以通过jsonobject够着json:
jsonobject jsonobject = new jsonobject();
jsonobject.put("blog", "");
jsonobject.put("author", "iteblog");
如果需要使用post方式来发送这个数据,我们可以如下实现:
private httpmethodbase createmethod(string url, int timeout) {
postmethod method = null;
try {
method = new postmethod(url);
jsonobject jsonobject = new jsonobject();
jsonobject.put("blog", "");
jsonobject.put("author", "iteblog");
string transjson = jsonobject.tostring();
requestentity se = new stringrequestentity(transjson, "application/json", "utf-8");
method.setrequestentity(se);
//使用系统提供的默认的恢复策略
method.getparams().setparameter(httpmethodparams.retry_handler, new defaulthttpmethodretryhandler());
//设置超时的时间
method.getparams().setparameter(httpmethodparams.so_timeout, timeout);
} catch (illegalargumentexception e) {
logger.error("非法的url:{}", url);
} catch (unsupportedencodingexception e) {
e.printstacktrace();
}
return method;
}
我们通过stringrequestentity来构造请求实体,在这里,stringrequestentity将接收三个参数,如下:
public stringrequestentity(string content, string contenttype, string charset)
throws unsupportedencodingexception
其中参数content就是我们需要传输的数据;contenttype是传送数据的格式,因为我们的数据格式是json的,所以contenttype必须填写application/json(更多的contenttype可以参见《http content-type常用一览表》);charset是字符集编码。
然后我们再通过httpclient对象的executemethod方法来执行:
int statuscode = httpclient.executemethod(getmethod);
//只要在获取源码中,服务器返回的不是200代码,则统一认为抓取源码失败,返回null。
if (statuscode != httpstatus.sc_ok) {
logger.error("method failed: " + getmethod.getstatusline() + "\tstatuscode: " + statuscode);
return null;
}
pom.xml文件的关键内容
commons-httpclient
commons-httpclient
3.1
org.apache.httpcomponents
httpcore
4.3.1
com.google.guava
guava
14.0.1
org.json
json
20140107
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯