JAVA发送http get/post请求,调用http接口、方法详解
程序员文章站
2023-12-09 18:24:45
三个例子 —java发送http get/post请求,调用http接口、方法
例1:使用 httpclient (commons-httpclient-3.0.jar...
三个例子 —java发送http get/post请求,调用http接口、方法
例1:使用 httpclient (commons-httpclient-3.0.jar
jar下载地址:
import java.io.bytearrayinputstream; import java.io.bytearrayoutputstream; import java.io.ioexception; import java.io.inputstream; import org.apache.commons.httpclient.httpclient; import org.apache.commons.httpclient.methods.inputstreamrequestentity; import org.apache.commons.httpclient.methods.postmethod; import org.apache.commons.httpclient.methods.requestentity; public class httptool { /** * 发送post请求 * * @author michael -----csdn: http://blog.csdn.net/capmiachael * @param params * 参数 * @param requesturl * 请求地址 * @param authorization * 授权书 * @return 返回结果 * @throws ioexception */ public static string sendpost(string params, string requesturl, string authorization) throws ioexception { byte[] requestbytes = params.getbytes("utf-8"); // 将参数转为二进制流 httpclient httpclient = new httpclient();// 客户端实例化 postmethod postmethod = new postmethod(requesturl); //设置请求头authorization postmethod.setrequestheader("authorization", "basic " + authorization); // 设置请求头 content-type postmethod.setrequestheader("content-type", "application/json"); inputstream inputstream = new bytearrayinputstream(requestbytes, 0, requestbytes.length); requestentity requestentity = new inputstreamrequestentity(inputstream, requestbytes.length, "application/json; charset=utf-8"); // 请求体 postmethod.setrequestentity(requestentity); httpclient.executemethod(postmethod);// 执行请求 inputstream soapresponsestream = postmethod.getresponsebodyasstream();// 获取返回的流 byte[] datas = null; try { datas = readinputstream(soapresponsestream);// 从输入流中读取数据 } catch (exception e) { e.printstacktrace(); } string result = new string(datas, "utf-8");// 将二进制流转为string // 打印返回结果 // system.out.println(result); return result; } /** * 从输入流中读取数据 * * @param instream * @return * @throws exception */ public static byte[] readinputstream(inputstream instream) throws exception { bytearrayoutputstream outstream = new bytearrayoutputstream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = instream.read(buffer)) != -1) { outstream.write(buffer, 0, len); } byte[] data = outstream.tobytearray(); outstream.close(); instream.close(); return data; } }
例2:
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.io.unsupportedencodingexception; import java.net.httpurlconnection; import java.net.inetsocketaddress; import java.net.proxy; import java.net.url; import java.net.urlconnection; import java.util.list; import java.util.map; /** * http请求工具类 * @author snowfigure * @since 2014-8-24 13:30:56 * @version v1.0.1 */ public class httprequestutil { static boolean proxyset = false; static string proxyhost = "127.0.0.1"; static int proxyport = 8087; /** * 编码 * @param source * @return */ public static string urlencode(string source,string encode) { string result = source; try { result = java.net.urlencoder.encode(source,encode); } catch (unsupportedencodingexception e) { e.printstacktrace(); return "0"; } return result; } public static string urlencodegbk(string source) { string result = source; try { result = java.net.urlencoder.encode(source,"gbk"); } catch (unsupportedencodingexception e) { e.printstacktrace(); return "0"; } return result; } /** * 发起http请求获取返回结果 * @param req_url 请求地址 * @return */ public static string httprequest(string req_url) { stringbuffer buffer = new stringbuffer(); try { url url = new url(req_url); httpurlconnection httpurlconn = (httpurlconnection) url.openconnection(); httpurlconn.setdooutput(false); httpurlconn.setdoinput(true); httpurlconn.setusecaches(false); httpurlconn.setrequestmethod("get"); httpurlconn.connect(); // 将返回的输入流转换成字符串 inputstream inputstream = httpurlconn.getinputstream(); inputstreamreader inputstreamreader = new inputstreamreader(inputstream, "utf-8"); bufferedreader bufferedreader = new bufferedreader(inputstreamreader); string str = null; while ((str = bufferedreader.readline()) != null) { buffer.append(str); } bufferedreader.close(); inputstreamreader.close(); // 释放资源 inputstream.close(); inputstream = null; httpurlconn.disconnect(); } catch (exception e) { system.out.println(e.getstacktrace()); } return buffer.tostring(); } /** * 发送http请求取得返回的输入流 * @param requesturl 请求地址 * @return inputstream */ public static inputstream httprequestio(string requesturl) { inputstream inputstream = null; try { url url = new url(requesturl); httpurlconnection httpurlconn = (httpurlconnection) url.openconnection(); httpurlconn.setdoinput(true); httpurlconn.setrequestmethod("get"); httpurlconn.connect(); // 获得返回的输入流 inputstream = httpurlconn.getinputstream(); } catch (exception e) { e.printstacktrace(); } return inputstream; } /** * 向指定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 的形式。 * @param isproxy * 是否使用代理模式 * @return 所代表远程资源的响应结果 */ public static string sendpost(string url, string param,boolean isproxy) { outputstreamwriter out = null; bufferedreader in = null; string result = ""; try { url realurl = new url(url); httpurlconnection conn = null; if(isproxy){//使用代理模式 @suppresswarnings("static-access") proxy proxy = new proxy(proxy.type.direct.http, new inetsocketaddress(proxyhost, proxyport)); conn = (httpurlconnection) realurl.openconnection(proxy); }else{ conn = (httpurlconnection) realurl.openconnection(); } // 打开和url之间的连接 // 发送post请求必须设置如下两行 conn.setdooutput(true); conn.setdoinput(true); conn.setrequestmethod("post"); // post方法 // 设置通用的请求属性 conn.setrequestproperty("accept", "*/*"); conn.setrequestproperty("connection", "keep-alive"); conn.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)"); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.connect(); // 获取urlconnection对象对应的输出流 out = new outputstreamwriter(conn.getoutputstream(), "utf-8"); // 发送请求参数 out.write(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; } public static void main(string[] args) { //demo:代理访问 string url = "http://api.adf.ly/api.php"; string para = "key=youkeyid&youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com"; string sr=httprequestutil.sendpost(url,para,true); system.out.println(sr); } }
例3
/** * 发送http post请求 * * @param xmlinfo * json转化成的字符串 * @param url * 请求url * @return 返回信息 */ public static string dohttppost(string xmlinfo, string url) { system.out.println("发起的数据:" + xmlinfo); byte[] xmldata = xmlinfo.getbytes(); inputstream instr = null; java.io.bytearrayoutputstream out = null; try { url url = new url(url); urlconnection urlcon = url.openconnection(); urlcon.setdooutput(true); urlcon.setdoinput(true); urlcon.setusecaches(false); urlcon.setrequestproperty("content-type", "application/json"); urlcon.setrequestproperty("charset", "utf-8"); urlcon.setrequestproperty("content-length", string.valueof(xmldata.length)); system.out.println(string.valueof(xmldata.length)); dataoutputstream printout = new dataoutputstream( urlcon.getoutputstream()); printout.write(xmldata); printout.flush(); printout.close(); instr = urlcon.getinputstream(); byte[] bis = ioutils.tobytearray(instr); string responsestring = new string(bis, "utf-8"); if ((responsestring == null) || ("".equals(responsestring.trim()))) { system.out.println("返回空"); } system.out.println("返回数据为:" + responsestring); return responsestring; } catch (exception e) { e.printstacktrace(); return "0"; } finally { try { out.close(); instr.close(); } catch (exception ex) { return "0"; } } }
以上所述是小编给大家介绍的java发送http get/post请求调用接口/方法详解整合,希望对大家有所帮助
推荐阅读
-
JAVA发送http get/post请求,调用http接口、方法详解
-
python通过get,post方式发送http请求和接收http响应的方法
-
nodejs使用http模块发送get与post请求的方法示例
-
Java 发送http请求(get、post)的示例
-
python通过get,post方式发送http请求和接收http响应的方法
-
python通过get,post方式发送http请求和接收http响应的方法
-
python通过get,post方式发送http请求和接收http响应的方法
-
java发送http的get、post请求 javagetpost
-
Java用HttpClient4发送http/https协议get/post请求,发送map,json,xml,txt数据
-
在Java中使用Get/Post方式发送Http请求