您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java:http请求(代码详解)

2026/1/27 5:13:25发布13次查看
java原生api
public class httprequest { /** * 向指定url发送get方法的请求 * * @param url * 发送请求的url * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return url 所代表远程资源的响应结果 */ public static string sendget(string url, string param) { string result = ""; bufferedreader in = null; try { string urlnamestring = url + "?" + param; url realurl = new url(urlnamestring); // 打开和url之间的连接 urlconnection connection = realurl.openconnection(); // 设置通用的请求属性 connection.setrequestproperty("accept", "*/*"); connection.setrequestproperty("connection", "keep-alive"); connection.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 map<string, list<string>> map = connection.getheaderfields(); // 遍历所有的响应头字段 for (string key : map.keyset()) { system.out.println(key + "--->" + map.get(key)); } // 定义 bufferedreader输入流来读取url的响应 in = new bufferedreader(new inputstreamreader( connection.getinputstream())); string line; while ((line = in.readline()) != null) { result += line; } } catch (exception e) { system.out.println("发送get请求出现异常!" + e); e.printstacktrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (exception e2) { e2.printstacktrace(); } } return result; } /** * 向指定 url 发送post方法的请求 * * @param url * 发送请求的 url * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static string sendpost(string url, string param) { printwriter out = null; bufferedreader in = null; string result = ""; try { url realurl = new url(url); // 打开和url之间的连接 urlconnection conn = realurl.openconnection(); // 设置通用的请求属性 conn.setrequestproperty("accept", "*/*"); conn.setrequestproperty("connection", "keep-alive"); conn.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); // 发送post请求必须设置如下两行 conn.setdooutput(true); conn.setdoinput(true); // 获取urlconnection对象对应的输出流 out = new printwriter(conn.getoutputstream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义bufferedreader输入流来读取url的响应 in = new bufferedreader( new inputstreamreader(conn.getinputstream())); string line; while ((line = in.readline()) != null) { result += line; } } catch (exception e) { system.out.println("发送 post 请求出现异常!"+e); e.printstacktrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(ioexception ex){ ex.printstacktrace(); } } return result; } /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub //发送 get 请求// string s=httprequest.sendget("http://ws.webxml.com.cn/webservices/mobilecodews.asmx/getmobilecodeinfo", "mobilecode=13069208531&userid=");// system.out.println(s); //发送 post 请求 string sr=httprequest.sendpost("http://ws.webxml.com.cn/webservices/mobilecodews.asmx/getmobilecodeinfo", "mobilecode=13069208531&userid="); system.out.println(sr); }}
httpclient 需要jar包:
public class httputils { private final static logger logger = logger.getlogger(httputils.class); private final static string operater_name = "【http操作】"; private final static int success = 200; private final static string utf8 = "utf-8"; private httpclient client; private final string respondtypexml = "application/x-www-form-urlencoded"; private final string respondtypejson = "application/json;charse=utf-8"; private static httputils instance = new httputils(); private httputils() { httpconnectionmanager httpconnectionmanager = new multithreadedhttpconnectionmanager(); httpconnectionmanagerparams params = httpconnectionmanager.getparams(); params.setconnectiontimeout(5000); params.setsotimeout(20000); params.setdefaultmaxconnectionsperhost(1000); params.setmaxtotalconnections(1000); client = new httpclient(httpconnectionmanager); client.getparams().setcontentcharset(utf8); client.getparams().sethttpelementcharset(utf8); } public static string get(url url) { return instance.doget(url); } private string doget(url url) { long begintime = system.currenttimemillis(); string respstr = ""; httpmethod method = null; try { logger.info(operater_name + "开始get通信,目标host:" + url); method = new getmethod(url.tostring()); // 中文转码 method.getparams().setcontentcharset(utf8); try { client.executemethod(method); } catch (httpexception e) { logger.error(new stringbuffer("发送http get给\r\n").append(url) .append("\r\nhttp异常\r\n"), e); } catch (ioexception e) { logger.error(new stringbuffer("发送http get给\r\n").append(url) .append("\r\nio异常\r\n"), e); } if (method.getstatuscode() == success) { respstr = method.getresponsebodyasstring(); } logger.info(operater_name + "通讯完成,返回码:" + method.getstatuscode()); logger.info(operater_name + "返回内容:" + method.getresponsebodyasstring()); logger.info(operater_name + "结束..返回结果:" + respstr); } catch (exception e) { logger.info(operater_name, e); }finally{ if(method != null){ method.releaseconnection(); } } long endtime = system.currenttimemillis(); logger.info(operater_name + "共计耗时:" + (endtime - begintime) + "ms"); return respstr; } /** * post请求 */ public static string post(url url, string content) { return instance.dopost(url, content); } private string dopost(url url, string content) { long begintime = system.currenttimemillis(); string respstr = ""; postmethod post = null; try { logger.info(operater_name + "开始post通信,目标host:" + url.tostring()); logger.info("通信内容:" + content); post = new postmethod(url.tostring()); requestentity requestentity = new stringrequestentity(content, respondtypexml, utf8); post.setrequestentity(requestentity); // 设置格式 post.getparams().setcontentcharset(utf8); client.executemethod(post); if (post.getstatuscode() == success) { respstr = post.getresponsebodyasstring(); } logger.info(operater_name + "通讯完成,返回码:" + post.getstatuscode()); logger.info(operater_name + "返回内容:" + post.getresponsebodyasstring()); logger.info(operater_name + "结束..返回结果:" + respstr); post.releaseconnection(); } catch (exception e) { logger.error(operater_name, e); }finally{ if(post != null){ post.releaseconnection(); } } long endtime = system.currenttimemillis(); logger.info(operater_name + "共计耗时:" + (endtime - begintime) + "ms"); return respstr; } /** * @param args * @throws malformedurlexception */ public static void main(string[] args) throws malformedurlexception { // todo auto-generated method stub jsonobject json = new jsonobject(); json.put("mobilecode", "13069208531"); json.put("userid", ""); url url = new url("http://ws.webxml.com.cn/webservices/mobilecodews.asmx/getmobilecodeinfo");// url url = new url("http://ws.webxml.com.cn/webservices/mobilecodews.asmx"// + "/getmobilecodeinfo?mobilecode=13069208531&userid="); string resp = post(url, json.tostring()); //string resp = get(url); system.out.println("resp:"+resp); }}
httpclient:
public class httpclientutil { public static void get(string number) throws exception{ httpclient client = new httpclient(); getmethod get = new getmethod("http://ws.webxml.com.cn/webservices/mobilecodews.asmx" + "/getmobilecodeinfo?mobilecode=" + number + "&userid="); // 指定传输的格式为get请求格式 get.setrequestheader("content-type", "text/xml; charset=utf-8"); // 发送请求 int code = client.executemethod(get); system.out.println("http:状态码为:" + code); string result = get.getresponsebodyasstring(); system.out.println("返回的结果为:" + result); } public static void post(string number) throws exception { //httpclient:在java代码中模拟http请求 // 创建浏览器对象 httpclient client = new httpclient(); // 填写数据,发送get或者post请求 postmethod post = new postmethod("http://ws.webxml.com.cn/webservices/mobilecodews.asmx/getmobilecodeinfo"); // 指定传输的格式为默认post格式 post.setrequestheader("content-type", "application/x-www-form-urlencoded"); // 传输参数 post.setparameter("mobilecode", number); post.setparameter("userid", ""); // 发送请求 int code = client.executemethod(post); system.out.println("http:状态码为:" + code); string result = post.getresponsebodyasstring(); system.out.println("返回的结果为:" + result); } /** * @description soap post方式请求,但是传输的数据为xml格式,有利于数据的维护 * @param number * @throws exception */ //它有两个版本soap1.1和soap1.2,jdk1.7及以上才可以使用soap1.2。 public void soap(string number) throws exception { //httpclient:在java代码中模拟http请求 // 创建浏览器对象 httpclient client = new httpclient(); // 填写数据,发送get或者post请求 postmethod post = new postmethod("http://ws.webxml.com.cn/webservices/mobilecodews.asmx"); // 指定传输的格式为xml格式 post.setrequestheader("content-type", "application/soap+xml;charset=utf-8"); // 传输xml,加载soap.txt inputstream in = httpclientutil.class.getclassloader().getresourceasstream("/soap.txt");//返回值是一个inputstream post.setrequestbody(in); // 发送请求 int code = client.executemethod(post); system.out.println("http:状态码为:" + code); string result = post.getresponsebodyasstring(); // 如果采用的是soap,则返回的数据也是基于xml的soap格式 system.out.println("返回的结果为:" + result); } //wsimport -s . -p com.hexy.ws http://ws.webxml.com.cn/webservices/mobilecodews.asmx?wsdl public static void wsdl(){ // 获取一个ws服务 mobilecodews ws = new mobilecodews(); // 获取具体的服务类型:get post soap1.1 soap1.2 mobilecodewssoap wssoap = ws.getmobilecodewssoap(); string address = wssoap.getmobilecodeinfo("18312345678", null); system.out.println("手机归属地信息为:" + address); } /** * @param args * @throws exception */ public static void main(string[] args) throws exception { // todo auto-generated method stub post("18312345678"); //wsdl(); //soap("18312345678"); }}
soap.txt
<?xml version="1.0" encoding="utf-8"?><soap12:envelope xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:body> <getmobilecodeinfo xmlns="http://webxml.com.cn/"> <mobilecode>13069208531</mobilecode> <userid></userid> </getmobilecodeinfo> </soap12:body></soap12:envelope>
相关推荐:
网络 - java 异步http请求。
java与http协议的详解
以上就是java:http请求(代码详解)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product