java發送url要求獲得前往值的二種辦法。本站提示廣大學習愛好者:(java發送url要求獲得前往值的二種辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是java發送url要求獲得前往值的二種辦法正文
上面供給二種辦法會應用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;
}