下面提供二种方法会使用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
}
总结:多练习代码,熟练之后才能更快速的去了解代码的学习的方法。多去获取一些思维方面的书籍可以看看。
可以用以下代码参考一下,如何获取URL返回状态码:
// 用getResponseCode可以获取URL返回状态码String surl = ""
try {
surl="你的url"
URL url = new URL(surl)
URLConnection rulConnection = url.openConnection()
HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection
httpUrlConnection.setConnectTimeout(300000)
httpUrlConnection.setReadTimeout(300000)
httpUrlConnection.connect()
String code = new Integer(httpUrlConnection.getResponseCode()).toString()
String message = httpUrlConnection.getResponseMessage()
System.out.println("getResponseCode code ="+ code)
System.out.println("getResponseMessage message ="+ message)
if(!code.startsWith("2")){
throw new Exception("ResponseCode is not begin with 2,code="+code)
}
System.out.println(getCurDateTime()+"连接"+surl+"正常")
}catch(Exception ex){
System.out.println(ex.getMessage())
}
try{
//URL url=new URL("http://www.youdao.com/smartresult-xml/search.s?type=ip&q=58.214.5.162")
URL url=new URL("http://whois.pconline.com.cn/ip.jsp?ip="+ip)
HttpURLConnection connect=(HttpURLConnection)url.openConnection()
InputStream is = connect.getInputStream()
ByteArrayOutputStream outStream = new ByteArrayOutputStream()
byte[] buff = new byte[256]
int rc = 0
while ( (rc = is.read(buff, 0, 256)) >0) {
outStream.write(buff, 0, rc)
}
byte[] b = outStream.toByteArray()
//关闭
outStream.close()
is.close()
connect.disconnect()
String address =new String(b)
if(address.indexOf("省")!=-1)
{
ipprovince =address.substring(0,address.indexOf("省")+1)
System.out.println("省地址为:"+ipprovince)
}else if(address.indexOf("区")!=-1)
{
ipprovince =address.substring(0,address.indexOf("区")+1)
System.out.println("省地址为:"+ipprovince)
}else
{
ipprovince =
address.substring(0,address.indexOf("市")+1)
System.out.println("省地址为:"+ipprovince)
}
}catch(Exception e){
e.printStackTrace()
}