欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-31 13:12:28
下面提供二种方法会使用java发送url请求,并获取服务器返回的值第一种方法:复制代码 代码如下:import org.apache.http.httpentity;imp...

下面提供二种方法会使用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;
}