当前位置: 移动技术网 > IT编程>开发语言>Java > java发送url请求获取返回值的二种方法

java发送url请求获取返回值的二种方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

下面提供二种方法会使用java发送url请求,并获取服务器返回的值

第一种方法:

复制代码 代码如下:

import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.httpclient;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httppost;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.params.coreconnectionpnames;
import org.apache.http.util.entityutils;

publicstaticstringsendurlrequest(stringurlstr,stringparam1,stringparam2)throwsexception{
stringtempstr=null;
httpclienthttpclient=newdefaulthttpclient();
propertiesproperties=newproperties();
httpentityentity=null;
stringxmlcontent="";
try
{

//设置超时时间
httpclient.getparams().setintparameter(coreconnectionpnames.connection_timeout,20000);
httpclient.getparams().setparameter(coreconnectionpnames.so_timeout,20000);

//封装需要传递的参数
list<namevaluepair>nvps=newarraylist<namevaluepair>();
nvps.add(newbasicnamevaluepair("mainmemocode",strmainmemocode));
nvps.add(newbasicnamevaluepair("recordpassword",strrecordpassword));
//客户端的请求方法类型
httpposthttppost=newhttppost(urlstr);
httppost.setentity(newurlencodedformentity(nvps,"gbk"));
httpresponseresponse=httpclient.execute(httppost);

//获取服务器返回http的content-type的值
tempstr=response.getheaders("content-type")[0].getvalue().tostring();

//获取服务器返回页面的值
entity=response.getentity();
xmlcontent=entityutils.tostring(entity);
stringstrmessage=null;
system.out.println(xmlcontent);
system.out.println(response.getheaders("content-type")[0].getvalue().tostring());
httppost.abort();

}
catch(sockettimeoutexceptione)
{
}
catch(exceptionex)
{
ex.printstacktrace();
}
finally{
httpclient.getconnectionmanager().shutdown();
}

第二种方法:

复制代码 代码如下:

publicstaticstringsendurlrequest(stringurlstr,stringparam1,stringparam2)throwsexception{

httpurlconnectionurl_con=null;
try{
urlurl=newurl(urlstr);
stringbufferbankxmlbuffer=newstringbuffer();
//创建url连接,提交到数据,获取返回结果
httpurlconnectionconnection=(httpurlconnection)url.openconnection();
connection.setrequestmethod("post");
connection.setdooutput(true);
connection.setrequestproperty("user-agent","directclient");

printwriterout=newprintwriter(newoutputstreamwriter(connection.getoutputstream(),"gbk"));
out.println(param);
out.close();
bufferedreaderin=newbufferedreader(newinputstreamreader(connection
.getinputstream(),"gbk"));

stringinputline;

while((inputline=in.readline())!=null){
bankxmlbuffer.append(inputline);
}
in.close();
tempstr=bankxmlbuffer.tostring();
}
catch(exceptione)
{
system.out.println("发送get请求出现异常!"+e);
e.printstacktrace();

}finally{
if(url_con!=null)
url_con.disconnect();
}

returntmpestr;
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网