您好,欢迎访问一九零五行业门户网

JAVA发送HTTP请求的方式有哪些

1. httpurlconnection使用jdk原生提供的net,无需其他jar包,代码如下:
import com.alibaba.fastjson.json;import java.io.bufferedreader;import java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import java.net.httpurlconnection;import java.net.url;import java.util.hashmap;import java.util.map; public class httptest1 { public static void main(string[] args) { httpurlconnection con = null; bufferedreader buffer = null; stringbuffer resultbuffer = null; try { url url = new url("http://10.30.10.151:8012/gateway.do"); //得到连接对象 con = (httpurlconnection) url.openconnection(); //设置请求类型 con.setrequestmethod("post"); //设置content-type,此处根据实际情况确定 con.setrequestproperty("content-type", "application/x-www-form-urlencoded"); //允许写出 con.setdooutput(true); //允许读入 con.setdoinput(true); //不使用缓存 con.setusecaches(false); outputstream os = con.getoutputstream(); map paramap = new hashmap(); paramap.put("type", "wx"); paramap.put("mchid", "10101"); //组装入参 os.write(("consumerappid=test&servicename=querymerchantservice&params=" + json.tojsonstring(paramap)).getbytes()); //得到响应码 int responsecode = con.getresponsecode(); if (responsecode == httpurlconnection.http_ok) { //得到响应流 inputstream inputstream = con.getinputstream(); //将响应流转换成字符串 resultbuffer = new stringbuffer(); string line; buffer = new bufferedreader(new inputstreamreader(inputstream, "gbk")); while ((line = buffer.readline()) != null) { resultbuffer.append(line); } system.out.println("result:" + resultbuffer.tostring()); } } catch (exception e) { e.printstacktrace(); } }}
2. httpclient需要用到commons-httpclient-3.1.jar,maven依赖如下:
<dependency> <groupid>commons-httpclient</groupid> <artifactid>commons-httpclient</artifactid> <version>3.1</version></dependency>
代码如下:
import com.alibaba.fastjson.json;import org.apache.commons.httpclient.httpclient;import org.apache.commons.httpclient.methods.postmethod; import java.io.ioexception;import java.util.hashmap;import java.util.map; public class httptest2 { public static void main(string[] args) { httpclient httpclient = new httpclient(); postmethod postmethod = new postmethod("http://10.30.10.151:8012/gateway.do"); postmethod.addrequestheader("accept", "*/*"); //设置content-type,此处根据实际情况确定 postmethod.addrequestheader("content-type", "application/x-www-form-urlencoded"); //必须设置下面这个header //添加请求参数 map paramap = new hashmap(); paramap.put("type", "wx"); paramap.put("mchid", "10101"); postmethod.addparameter("consumerappid", "test"); postmethod.addparameter("servicename", "querymerchantservice"); postmethod.addparameter("params", json.tojsonstring(paramap)); string result = ""; try { int code = httpclient.executemethod(postmethod); if (code == 200){ result = postmethod.getresponsebodyasstring(); system.out.println("result:" + result); } } catch (ioexception e) { e.printstacktrace(); } }}
3. closeablehttpclient需要用到httpclient-4.5.6.jar,maven依赖如下:
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5.6</version></dependency>
代码如下:
import com.alibaba.fastjson.json;import org.apache.http.consts;import org.apache.http.httpentity;import org.apache.http.namevaluepair;import org.apache.http.client.config.requestconfig;import org.apache.http.client.entity.urlencodedformentity;import org.apache.http.client.methods.closeablehttpresponse;import org.apache.http.client.methods.httppost;import org.apache.http.impl.client.closeablehttpclient;import org.apache.http.impl.client.httpclients;import org.apache.http.message.basicnamevaluepair;import org.apache.http.util.entityutils; import java.io.ioexception;import java.util.arraylist;import java.util.hashmap;import java.util.list;import java.util.map; public class httptest3 { public static void main(string[] args) { int timeout = 120000; closeablehttpclient httpclient = httpclients.createdefault(); requestconfig defaultrequestconfig = requestconfig.custom().setconnecttimeout(timeout) .setconnectionrequesttimeout(timeout).setsockettimeout(timeout).build(); httppost httppost = null; list<namevaluepair> nvps = null; closeablehttpresponse responses = null;// 命名冲突,换一个名字,response httpentity resentity = null; string result; try { httppost = new httppost("http://10.30.10.151:8012/gateway.do"); httppost.setconfig(defaultrequestconfig); map paramap = new hashmap(); paramap.put("type", "wx"); paramap.put("mchid", "10101"); nvps = new arraylist<namevaluepair>(); nvps.add(new basicnamevaluepair("consumerappid", "test")); nvps.add(new basicnamevaluepair("servicename", "querymerchantservice")); nvps.add(new basicnamevaluepair("params", json.tojsonstring(paramap))); httppost.setentity(new urlencodedformentity(nvps, consts.utf_8)); responses = httpclient.execute(httppost); resentity = responses.getentity(); result = entityutils.tostring(resentity, consts.utf_8); entityutils.consume(resentity); system.out.println("result:" + result); } catch (exception e) { e.printstacktrace(); } finally { try { responses.close(); httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } }}
4. okhttp需要用到okhttp-3.10.0.jar,maven依赖如下:
<dependency> <groupid>com.squareup.okhttp3</groupid> <artifactid>okhttp</artifactid> <version>3.10.0</version></dependency>
代码如下:
import com.alibaba.fastjson.json;import okhttp3.*; import java.io.ioexception;import java.util.hashmap;import java.util.map; public class httptest4 { public static void main(string[] args) throws ioexception { string url = "http://10.30.10.151:8012/gateway.do"; okhttpclient client = new okhttpclient(); map paramap = new hashmap(); paramap.put("yybh", "1231231"); requestbody requestbody = new multipartbody.builder() .addformdatapart("consumerappid", "tst") .addformdatapart("servicename", "querycipher") .addformdatapart("params", json.tojsonstring(paramap)) .build(); request request = new request.builder() .url(url) .post(requestbody) .addheader("content-type", "application/x-www-form-urlencoded") .build(); response response = client .newcall(request) .execute(); if (response.issuccessful()) { system.out.println("result:" + response.body().string()); } else { throw new ioexception("unexpected code " + response); } }}
5. socket使用jdk原生提供的net,无需其他jar包
代码如下:
import com.alibaba.fastjson.json; import java.io.ioexception;import java.io.inputstream;import java.io.outputstreamwriter;import java.net.socket;import java.net.urlencoder;import java.net.unknownhostexception;import java.util.arraylist;import java.util.hashmap;import java.util.map; public class httptest6 { private static string encoding = "utf-8"; public static void main(string[] args) { try { map paramap = new hashmap(); paramap.put("yybh", "12312311"); string data = urlencoder.encode("consumerappid", "utf-8") + "=" + urlencoder.encode("test", "utf-8") + "&" + urlencoder.encode("servicename", "utf-8") + "=" + urlencoder.encode("querycipher", "utf-8") + "&" + urlencoder.encode("params", "utf-8") + "=" + urlencoder.encode(json.tojsonstring(paramap), "utf-8"); socket s = new socket("10.30.10.151", 8012); outputstreamwriter osw = new outputstreamwriter(s.getoutputstream()); stringbuffer sb = new stringbuffer(); sb.append("post /gateway.do http/1.1\r\n"); sb.append("host: 10.30.10.151:8012\r\n"); sb.append("content-length: " + data.length() + "\r\n"); sb.append("content-type: application/x-www-form-urlencoded\r\n"); //注,这里很关键。这里一定要一个回车换行,表示消息头完,不然服务器会等待 sb.append("\r\n"); osw.write(sb.tostring()); osw.write(data); osw.write("\r\n"); osw.flush(); //--输出服务器传回的消息的头信息 inputstream is = s.getinputstream(); string line = null; int contentlength = 0;//服务器发送回来的消息长度 // 读取所有服务器发送过来的请求参数头部信息 do { line = readline(is, 0); //如果有content-length消息头时取出 if (line.startswith("content-length")) { contentlength = integer.parseint(line.split(":")[1].trim()); } //打印请求部信息 system.out.print(line); //如果遇到了一个单独的回车换行,则表示请求头结束 } while (!line.equals("\r\n")); //--输消息的体 system.out.print(readline(is, contentlength)); //关闭流 is.close(); } catch (unknownhostexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } /* * 这里我们自己模拟读取一行,因为如果使用api中的bufferedreader时,它是读取到一个回车换行后 * 才返回,否则如果没有读取,则一直阻塞,直接服务器超时自动关闭为止,如果此时还使用bufferedreader * 来读时,因为读到最后一行时,最后一行后不会有回车换行符,所以就会等待。如果使用服务器发送回来的 * 消息头里的content-length来截取消息体,这样就不会阻塞 * * contentle 参数 如果为0时,表示读头,读时我们还是一行一行的返回;如果不为0,表示读消息体, * 时我们根据消息体的长度来读完消息体后,客户端自动关闭流,这样不用先到服务器超时来关闭。 */ private static string readline(inputstream is, int contentle) throws ioexception { arraylist linebytelist = new arraylist(); byte readbyte; int total = 0; if (contentle != 0) { do { readbyte = (byte) is.read(); linebytelist.add(byte.valueof(readbyte)); total++; } while (total < contentle);//消息体读还未读完 } else { do { readbyte = (byte) is.read(); linebytelist.add(byte.valueof(readbyte)); } while (readbyte != 10); } byte[] tmpbytearr = new byte[linebytelist.size()]; for (int i = 0; i < linebytelist.size(); i++) { tmpbytearr[i] = ((byte) linebytelist.get(i)).bytevalue(); } linebytelist.clear(); return new string(tmpbytearr, encoding); }}
6. resttemplateresttemplate 是由spring提供的一个http请求工具。比传统的apache和httpclient便捷许多,能够大大提高客户端的编写效率。代码如下:
import org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.http.client.clienthttprequestfactory;import org.springframework.http.client.simpleclienthttprequestfactory;import org.springframework.web.client.resttemplate; @configurationpublic class resttemplateconfig { @bean public resttemplate resttemplate(clienthttprequestfactory factory){ return new resttemplate(factory); } @bean public clienthttprequestfactory simpleclienthttprequestfactory(){ simpleclienthttprequestfactory factory = new simpleclienthttprequestfactory(); factory.setconnecttimeout(15000); factory.setreadtimeout(5000); return factory; }} @autowiredresttemplate resttemplate; @testpublic void posttest() throws exception { multivaluemap<string, string> requestentity = new linkedmultivaluemap<>(); map paramap = new hashmap(); paramap.put("type", "wx"); paramap.put("mchid", "10101"); requestentity.add("consumerappid", "test"); requestentity.add("servicename", "querymerchant"); requestentity.add("params", json.tojsonstring(paramap)); resttemplate resttemplate = new resttemplate(); system.out.println(resttemplate.postforobject("http://10.30.10.151:8012/gateway.do", requestentity, string.class));}
以上就是java发送http请求的方式有哪些的详细内容。
其它类似信息

推荐信息