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);

//封装需要传递的参数Listnvps=newArrayList();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;}

Java中,你可以使用HttpURLConnection或者第三方库如Apache HttpClient或者OkHttp来发送POST请求获取响应。这里我们以HttpURLConnection为例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { private static final String POST_URL = "http://example.com/api/endpoint"; // 替换为你实际的URL public static void main(String[] args) throws Exception { URL url = new URL(POST_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 设置POST参数,例如这里是JSON格式 String postData = "{\"key\":\"value\"}"; byte[] bytes = postData.getBytes("UTF-8"); connection.setDoOutput(true); connection.getOutputStream().write(bytes); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应字符串 System.out.println("Response: " + response.toString()); } else { System.out.println("Failed to send POST request. Response code: " + responseCode); } connection.disconnect(); } } ``` 这段代码首先创建一个URL对象,然后通过HttpURLConnection对象连接到该URL并发起POST请求。如果HTTP状态码为200(成功),它将读取并打印出响应的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值