对于懒癌程序员而言,希望拿到手能用到的代码;稍微有点追求的,对于一些看起来比较蛋疼的代码,会想着能不能去优化,为什么一定要写这些一成不变的代码,能不能不写?我可以告诉你,网上很多博客的代码,其实是过时的,尽量别用百度,搜出来的东西,太尼玛坑!
对于一个函数,无非就是入参和返回,http请求也是如此。对于http请求的入参,HttpMethod提供了两种方法来设置参数
//会直接将String拼接到你的url之后 HttpMethod.setQueryString(String s) //将数组解析后拼接到参数中 HttpMethod.setQueryString(NameValuePair[] var1)
当然,你也可以更加粗暴,直接将参数写到url里面,这个就看对方怎么解析了。对方如果是从requestBody里面解析,有可能解析不到你的参数,这一点我并没有尝试。
这里有一个坑,如果你的url里面有了参数,之后调用setQueryString方法设置参数,会报错,源码跟进之后,会发现,拼接时加了?,具体代码如下:
public URI getURI() throws URIException { StringBuffer buffer = new StringBuffer(); if(this.httphost != null) { buffer.append(this.httphost.getProtocol().getScheme()); buffer.append("://"); buffer.append(this.httphost.getHostName()); int charset = this.httphost.getPort(); if(charset != -1 && charset != this.httphost.getProtocol().getDefaultPort()) { buffer.append(":"); buffer.append(charset); } } buffer.append(this.path); if(this.queryString != null) { buffer.append('?'); buffer.append(this.queryString); } String charset1 = this.getParams().getUriCharset(); return new URI(buffer.toString(), true, charset1); }
对于返回,api提供三方方式,分别返回String、byte[]、inputStream,不少博客里拿到inputStream之后读出byte[]再转成String,看到那些博客的时候,我觉得不合理,这种固定的代码,应该直接对外提供接口,稍微看了下方法,果然,api直接提供了。
private static void get() throws Exception { HttpClient client = new HttpClient(); HttpMethod getMethod = new GetMethod("http://www.baidu.com"); client.executeMethod(getMethod); //返回String getMethod.getResponseBodyAsString(); //返回byte[] getMethod.getResponseBody(); //返回InputStream,对于特别大的返回或者未知大小的返回,推荐用InputStream流读取 getMethod.getResponseBodyAsStream(); //不需要知道http的头如何设置,直接用String构造指定编码即可 new String(getMethod.getResponseBody(), "utf-8"); }
真正的用,还需要根据返回的状态码去读取,至于异常处理,这种底层方法的异常,直接往上抛即可。