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;

public static String sendUrlRequest(String urlStr, String param1,String param2) throws Exception {

String tempStr = null;

HttpClient httpclient = new DefaultHttpClient();

Properties properties = new Properties();

HttpEntity entity = null;

String xmlContent = "";

try

{

//设置超时时间

httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,20000);

httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);

//封装需要传递的参数

List nvps = new ArrayList ();

nvps.add(new BasicNameValuePair("mainMemoCode", strmainMemoCode));

nvps.add(new BasicNameValuePair("recordPassWord", strrecordPassWord));

//客户端的请求方法类型

HttpPost httpPost = new HttpPost(urlStr);

httpPost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));

HttpResponse response = httpclient.execute(httpPost);

//获取服务器返回Http的Content-Type的值

tempStr=response.getHeaders("Content-Type")[0].getValue().toString();

//获取服务器返回页面的值

entity = response.getEntity();

xmlContent = EntityUtils.toString(entity);

String strmessage=null;

System.out.println(xmlContent);

System.out.println(response.getHeaders("Content-Type")[0].getValue().toString());

httpPost.abort();

}

catch (SocketTimeoutException e)

{

}

catch(Exception ex)

{

ex.printStackTrace();

}

finally{

httpclient.getConnectionManager().shutdown();

}

第二种方法:

public static String sendUrlRequest(String urlStr, String param1,String param2) throws Exception {

HttpURLConnection url_con =null;

try {

URL url = new URL(urlStr);

StringBuffer bankXmlBuffer = new StringBuffer();

//创建URL连接,提交到数据,获取返回结果

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");

connection.setDoOutput(true);

connection.setRequestProperty("User-Agent", "directclient");

PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"GBK"));

out.println(param);

out.close();

BufferedReader in = new BufferedReader(new InputStreamReader(connection

.getInputStream(),"GBK"));

String inputLine;

while ((inputLine = in.readLine()) != null) {

bankXmlBuffer.append(inputLine);

}

in.close();

tempStr = bankXmlBuffer.toString();

}

catch(Exception e)

{

System.out.println("发送GET请求出现异常!" + e);

e.printStackTrace();

} finally {

if (url_con != null)

url_con.disconnect();

}

return tmpeStr;

}


版权声明:本文为weixin_42360972原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。