java发送put请求
答案:2 悬赏:40 手机版
解决时间 2021-03-14 17:24
- 提问者网友:饥饿走向夜
- 2021-03-13 20:48
java怎样发送put请求到应用程序
最佳答案
- 五星知识达人网友:独行浪子会拥风
- 2021-03-13 21:04
PUT请求是神马东东,我听说过POST请求
全部回答
- 1楼网友:躲不过心动
- 2021-03-13 22:37
java中用post,get,put请求方法:
public static string javahttpget(string url,string charset){
string resultdata = null;
try {
url pathurl = new url(url); //创建一个url对象
httpurlconnection urlconnect = (httpurlconnection) pathurl.openconnection(); //打开一个httpurlconnection连接
urlconnect.setconnecttimeout(30000); // 设置连接超时时间
urlconnect.connect();
if (urlconnect.getresponsecode() == 200) { //请求成功
resultdata = readinputstream(urlconnect.getinputstream(), charset);
}
} catch (malformedurlexception e) {
logl.getinstance().getlog().error("url出错!", e);
} catch (ioexception e) {
logl.getinstance().getlog().error("读取数据流出错!", e);
}
return resultdata;
}
public static string javahttppost(string url,map map,string charset){
string resultdata=null;
stringbuffer params = new stringbuffer();
try {
iterator> ir = map.entryset().iterator();
while (ir.hasnext()) {
map.entry entry = (map.entry) ir.next();
params.append(urlencoder.encode(entry.getkey(),charset) + "=" + urlencoder.encode(entry.getvalue().tostring(), charset) + "&");
}
byte[] postdata = params.deletecharat(params.length()).tostring().getbytes();
url pathurl = new url(url); //创建一个url对象
httpurlconnection urlconnect = (httpurlconnection) pathurl.openconnection();
urlconnect.setconnecttimeout(30000); // 设置连接超时时间
urlconnect.setdooutput(true); //post请求必须设置允许输出
urlconnect.setusecaches(false); //post请求不能使用缓存
urlconnect.setrequestmethod("post"); //设置post方式请求
urlconnect.setinstancefollowredirects(true);
urlconnect.setrequestproperty("content-type","application/x-www-form-urlencoded; charset="+charset);// 配置请求content-type
urlconnect.connect(); // 开始连接
dataoutputstream dos = new dataoutputstream(urlconnect.getoutputstream()); // 发送请求参数
dos.write(postdata);
dos.flush();
dos.close();
if (urlconnect.getresponsecode() == 200) { //请求成功
resultdata = readinputstream(urlconnect.getinputstream(),charset);
}
} catch (malformedurlexception e) {
logl.getinstance().getlog().error("url出错!", e);
} catch (ioexception e) {
logl.getinstance().getlog().error("读取数据流出错!", e);
} catch (exception e) {
logl.getinstance().getlog().error("post出错!", e);
}
return resultdata;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯