JAVA-用HttpClient来模拟浏览器GET,POST
JAVA实现简单的HTTP服务器端
writer.println("Accept-Encoding: gzip, deflate");
writer.println("Host: ");
writer.println("Connection: Keep-Alive");
writer.println();
writer.flush();
String line = reader.readLine();
writer.println("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
writer.println("GET /home.html HTTP/1.1&ln("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
javahttpput请求方式_使用HttpClient发送GETPOSTPUTDe
javahttpput请求方式_使用HttpClient发送GETPOSTPUTDe在Java中,我们可以使用HttpClient库来发送HTTP请求,包括GET、POST、PUT、DELETE等请求方式。
下面是使用HttpClient发送这些请求的示例代码。
1.发送GET请求:```javapublic class HttpGetExamplepublic static void main(String[] args) throws Exceptionint statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```2.发送POST请求:```javapublic class HttpPostExamplepublic static void main(String[] args) throws Exception//设置请求体StringEntity requestBody = new StringEntity("request body", "UTF-8");int statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```3.发送PUT请求:```javapublic class HttpPutExamplepublic static void main(String[] args) throws Exception//设置请求体StringEntity requestBody = new StringEntity("request body", "UTF-8");int statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```4.发送DELETE请求:```javapublic class HttpDeleteExamplepublic static void main(String[] args) throws Exceptionint statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```以上代码示例了如何使用HttpClient库发送GET、POST、PUT、DELETE请求,并处理响应数据。
java中的post的方法
java中的post的方法在Java中,HTTP POST方法用于向指定的URL提交数据。
它是用来向服务器提交数据,并在服务器上创建新的资源的一种请求方法。
在Java中,我们可以使用不同的方式来实现HTTP POST请求,包括使用原生的Java API、使用第三方库或框架等。
下面我们将介绍在Java中实现HTTP POST请求的一些常用方法。
1. 使用原生的Java API实现HTTP POST请求在Java中,我们可以使用原生的Java API来实现HTTP POST请求。
下面是一个简单的例子:javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import .HttpURLConnection;import .URL;import java.nio.charset.StandardCharsets;public class HttpPostExample {public static void main(String[] args) throws IOException { String url = "String data = "param1=value1¶m2=value2";byte[] postData = data.getBytes(StandardCharsets.UTF_8);int postDataLength = postData.length;URL obj = new URL(url);HttpURLConnection con = (HttpURLConnection)obj.openConnection();con.setDoOutput(true);con.setRequestMethod("POST");con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");con.setRequestProperty("Content-Length",Integer.toString(postDataLength));try (OutputStream os = con.getOutputStream()) {os.write(postData);}StringBuilder response = new StringBuilder();try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {String inputLine;while ((inputLine = in.readLine()) != null) {response.append(inputLine);}}System.out.println(response.toString());}}在上面的例子中,我们使用了`HttpURLConnection`来发送HTTP POST请求。
JAVA调用HTTP接口POST或GET实现方式
JAVA调⽤HTTP接⼝POST或GET实现⽅式HTTP是⼀个客户端和服务器端请求和应答的标准(TCP),客户端是终端⽤户,服务器端是⽹站。
通过使⽤Web浏览器、⽹络爬⾍或者其它的⼯具,客户端发起⼀个到服务器上指定端⼝(默认端⼝为80)的HTTP请求。
具体POST或GET实现代码如下:package com.yoodb.util;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import mons.httpclient.DefaultHttpMethodRetryHandler;import mons.httpclient.HttpClient;import mons.httpclient.HttpException;import mons.httpclient.methods.GetMethod;import mons.httpclient.methods.PostMethod;import mons.httpclient.params.HttpMethodParams;public class HttpConnectUtil {private static String DUOSHUO_SHORTNAME = "yoodb";//多说短域名 ****.yoodb.****private static String DUOSHUO_SECRET = "xxxxxxxxxxxxxxxxx";//多说秘钥/*** get⽅式* @param url* @author * @return*/public static String getHttp(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());try {httpClient.executeMethod(getMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = getMethod.getResponseBodyAsStream();int len = 0;byte[] buf = new byte[1024];while((len=in.read(buf))!=-1){out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//释放连接getMethod.releaseConnection();}return responseMsg;}/*** post⽅式* @param url* @param code* @param type* @author * @return*/public static String postHttp(String url,String code,String type) {String responseMsg = "";HttpClient httpClient = new HttpClient();httpClient.getParams().setContentCharset("GBK");PostMethod postMethod = new PostMethod(url);postMethod.addParameter(type, code);postMethod.addParameter("client_id", DUOSHUO_SHORTNAME);postMethod.addParameter("client_secret", DUOSHUO_SECRET);try {httpClient.executeMethod(postMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = postMethod.getResponseBodyAsStream();int len = 0;byte[] buf = new byte[1024];while((len=in.read(buf))!=-1){out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();}return responseMsg;}}1、下⾯说⼀下多说单点登录(SSO)获取access_token访问多说API的凭证。
request请求获取参数的实现方法(post和get两种方式)
request请求获取参数的实现方法(post和get两种方式)在Web开发中,GET和POST是两种常见的HTTP请求方法。
GET方法用于从服务器获取数据,而POST方法用于向服务器提交数据。
使用这两种方法请求时,可以通过URL传递参数(GET)或将参数添加到请求体中(POST)。
下面会详细介绍GET和POST请求获取参数的实现方法。
1.GET请求获取参数:GET请求将参数添加到请求URL的查询字符串中,参数之间使用"&"符号分隔。
可以通过多种方式进行参数传递,比如在URL中添加参数、使用表单元素的值等。
在后端服务中可以使用不同的语言(如Java、Python、Node.js等)来获取这些参数。
1.1在URL中添加参数:在后端服务中,可以使用以下方式来获取GET请求的参数:- Java Servlet:```javaString param1 = request.getParameter("param1");String param2 = request.getParameter("param2");```- Python Flask:```pythonfrom flask import requestparam1 = request.args.get('param1')param2 = request.args.get('param2')```- Node.js Express:```javascriptconst express = require('express');const app = express(;app.get('/path', (req, res) =>const param1 = req.query.param1;const param2 = req.query.param2;});```1.2使用表单元素的值:在HTML页面中,可以使用表单来传递GET请求的参数。
java的post,get,put,delete对应数据库用法
java的post,get,put,delete对应数据库用法一、引言在Java中,post,get,put,delete是常见的HTTP请求方法,用于在Web应用程序中进行数据交互。
而在数据库操作中,我们通常使用SQL语句来执行增删查改操作。
那么,如何将这几种HTTP请求方法与数据库操作结合起来呢?本文将详细介绍Java中的post,get,put,delete请求方法对应数据库的用法。
二、Java中的HTTP请求方法1. POST:用于提交数据到服务器,通常用于创建或更新数据。
2. GET:用于获取数据,通常用于查询服务器上的数据。
3. PUT:用于更新单个资源,通常用于更新服务器上的数据。
4. DELETE:用于删除资源,通常用于删除服务器上的数据。
三、数据库操作1. 插入(Insert):使用SQL语句的INSERT INTO...VALUES...将数据插入数据库表中。
对应GET请求方法,可通过查询数据库表获取需要插入的数据。
2. 查询(Select):使用SQL语句的SELECT...FROM...来查询数据库表中的数据。
对应POST和GET请求方法,可以提交查询条件到服务器,或者通过GET请求直接查询服务器上的数据。
3. 更新(Update):使用SQL语句的UPDATE...SET...WHERE...来更新数据库表中的数据。
对应PUT请求方法,可以提交需要更新的数据到服务器。
4. 删除(Delete):使用SQL语句的DELETE FROM...来删除数据库表中的数据。
对应DELETE请求方法,可以提交需要删除的数据到服务器。
四、Java代码示例以MySQL数据库为例,展示如何使用Java的post,get,put,delete请求方法进行数据库操作。
1. POST请求并插入数据:```java// 创建连接对象Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb ", "username", "password");// 创建PreparedStatement对象并执行插入操作PreparedStatement pstmt = conn.prepareStatement("INSERT INTO mytable (column1, column2) VALUES (?, ?)");pstmt.setString(1, "value1");pstmt.setString(2, "value2");pstmt.executeUpdate();```2. GET请求并查询数据:```java// 创建连接对象Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb ", "username", "password");// 创建Statement对象并执行查询操作Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("SELECT * FROM mytable WHERE column1 = 'value1'");// 处理查询结果集while (rs.next()) {// 输出查询到的数据System.out.println(rs.getString("column2"));}```3. PUT请求并更新数据:PUT请求和更新数据库表中的数据的示例代码相似于POST请求和插入数据的示例代码,只不过在SQL语句中使用了UPDATE...SET...WHERE...来更新数据。
解决java请求带headers的具体操作步骤-概述说明以及解释
解决java请求带headers的具体操作步骤-概述说明以及解释1.引言1.1 概述在进行Java网络编程时,我们经常需要向服务器发送HTTP请求,并在请求中附带一些自定义的头部信息(headers)。
HTTP请求头部可以包含诸如身份验证、请求类型、数据格式等重要信息,因此了解如何解决Java 请求带头部的问题是非常重要的。
本文将介绍如何在Java中进行HTTP请求时携带头部信息的具体操作步骤。
我们将探讨使用Java的标准库以及一些常用的第三方库来实现此功能。
无论是发送GET请求还是POST请求,我们都将讨论如何设置请求头部以满足我们的需求。
首先,我们将介绍Java标准库中的方法,这些方法提供了基本的HTTP 请求功能。
我们将学习如何创建HTTP连接、设置请求方法、添加头部信息等。
然后,我们将深入研究一些流行的第三方库,如Apache HttpClient 和OkHttp。
这些库提供了更简洁、更灵活的方式来发送HTTP请求并附带头部信息。
通过本文的学习,读者将能够掌握在Java中发送带头部信息的HTTP 请求的技巧和方法。
无论是向RESTful API发送请求还是与其他服务器进行交互,掌握如何设置请求头部信息是非常关键的。
接下来,我们将详细介绍如何进行这些操作,以便读者在实际开发中能够灵活运用。
1.2 文章结构文章结构部分应该包括对整篇文章结构的描述和各个章节的简要介绍。
以下是一个例子:2. 正文在本节中,我们将详细介绍解决Java请求带headers的具体操作步骤。
为了清晰地呈现该主题的内容,我们将文章分为以下几个要点:2.1 第一个要点在这一部分,我们将介绍如何设置请求头(headers)以及它们的作用。
我们将通过示例代码展示如何使用Java代码来添加不同类型的headers。
此外,我们还会讨论一些常见的header字段以及它们的用途和示例。
2.2 第二个要点第二个要点将更进一步探讨如何通过Java发送带headers的请求。
Java如何实现URL带请求参数(getpost)及得到get和post请求url和参数列表的方法
Java如何实现URL带请求参数(getpost)及得到get和post请求url和参数列表的⽅法具体代码如下所⽰:public static String sendGet(String url,String param){String result = "";try{String urlName = url + "?"+param;//URL U = new URL(urlName);URLConnection connection = U.openConnection();connection.connect();BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine())!= null){result += line;}in.close();}catch(Exception e){System.out.println("Helloword!!"+e);}return result;}public static String sendPost(String url,String param){String result="";try{URL httpurl = new URL(url);HttpURLConnection httpConn = (HttpURLConnection)httpurl.openConnection();httpConn.setDoOutput(true);httpConn.setDoInput(true);PrintWriter out = new PrintWriter(httpConn.getOutputStream());out.print(param);out.flush();out.close();BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));String line;while ((line = in.readLine())!= null){result += line;}in.close();}catch(Exception e){System.out.println("Helloword!"+e);}return result;}下⾯给⼤家介绍 java得到GET和POST请求URL和参数列表的⽅法在servlet中GET请求可以通过HttpServletRequest的getRequestURL⽅法和getQueryString()得到完整的请求路径和请求所有参数列表,POST的需要getParameterMap()⽅法遍历得到,不论GET或POST都可以通过getRequestURL+getParameterMap()来得到请求完整路径package com.zuidaimaimport java.io.IOException;import java.io.PrintWriter;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class GetParams extends HttpServlet {private static final long serialVersionUID = 1L;public GetParams() {super();}protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {PrintWriter writer = response.getWriter();writer.println("GET " + request.getRequestURL() + " "+ request.getQueryString());Map<String, String[]> params = request.getParameterMap();String queryString = "";for (String key : params.keySet()) {String[] values = params.get(key);for (int i = 0; i < values.length; i++) {String value = values[i];queryString += key + "=" + value + "&";}}// 去掉最后⼀个空格queryString = queryString.substring(0, queryString.length() - 1);writer.println("GET " + request.getRequestURL() + " " + queryString);}protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {PrintWriter writer = response.getWriter();Map<String, String[]> params = request.getParameterMap();String queryString = "";for (String key : params.keySet()) {String[] values = params.get(key);for (int i = 0; i < values.length; i++) {String value = values[i];queryString += key + "=" + value + "&";}}// 去掉最后⼀个空格queryString = queryString.substring(0, queryString.length() - 1);writer.println("POST " + request.getRequestURL() + " " + queryString);}}以上代码简单易懂,希望对⼤家学习 java post get url 请求参数的相关⽅法有所帮助,感谢⼤家⼀直以来对⽹站的⽀持,有你们的⽀持,我们会做的更好。
java 中post 和get方法
java 中post 和get方法
Java中的POST和GET方法是HTTP通信协议中常用的两种方法,分别用于向服务器发送数据和从服务器获取数据。
POST 方法是一种向服务器提交数据的方式,可以通过 HTTP 请求体传递请求参数。
对于大量数据的传递,POST 方法更为合适。
在Java 中,可以使用 HttpURLConnection 或 HttpClient 类来实现POST 请求。
GET 方法则是一种向服务器请求数据的方式,可以将请求参数通过 URL 传递。
GET 方法主要用于获取数据,对于数据的修改,应该使用 POST 方法。
在 Java 中,可以使用 URLConnection 或HttpClient 类来实现 GET 请求。
在使用 POST 和 GET 方法时,需要注意以下几点:
1. POST 方法适用于传输大量数据,而 GET 方法适用于传输小量数据。
2. POST 方法的请求参数通过请求体传递,而 GET 方法的请求参数通过 URL 传递,因此 GET 方法的请求参数会暴露在 URL 中。
3. POST 方法的请求参数可以是任意类型的数据,而 GET 方法的请求参数只能是字符串类型的数据。
4. POST 方法的请求可以提交文件等类型的数据,而 GET 方法只能提交文本数据。
总之,在选择使用 POST 或 GET 方法时,需要根据具体情况来决定使用哪种方法,以达到最好的效果。
java中的http请求的封装(GET、POST、form表单形式)
java中的http请求的封装(GET、POST、form表单形式)⽬前JAVA实现HTTP请求的⽅法⽤的最多的有两种:⼀种是通过HTTPClient这种第三⽅的开源框架去实现。
HTTPClient对HTTP的封装性⽐较不错,通过它基本上能够满⾜我们⼤部分的需求,HttpClient3.1 是 mons.httpclient下操作远程 url的⼯具包,虽然已不再更新,但实现⼯作中使⽤httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的⼯具包,最新的;另⼀种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA⽐较原⽣的⼀种实现⽅式。
第⼀种⽅式:java原⽣HttpURLConnectionpackage com.mobile.utils;import com.alibaba.fastjson.JSONObject;import org.apache.log4j.Logger;import java.io.*;import .HttpURLConnection;import .MalformedURLException;import .URL;import java.util.*;public class HttpUtil {static Logger log = Logger.getLogger(HttpUtil.class);/*** 向指定URL发送GET⽅法的请求** @param httpurl* 请求参数⽤?拼接在url后边,请求参数应该是 name1=value1&name2=value2 的形式。
* @return result 所代表远程资源的响应结果*/public static String doGet(String httpurl) {HttpURLConnection connection = null;InputStream is = null;BufferedReader br = null;String result = null;// 返回结果字符串try {// 创建远程url连接对象URL url = new URL(httpurl);// 通过远程url连接对象打开⼀个连接,强转成httpURLConnection类connection = (HttpURLConnection) url.openConnection();// 设置连接⽅式:getconnection.setRequestMethod("GET");// 设置连接主机服务器的超时时间:15000毫秒connection.setConnectTimeout(15000);// 设置读取远程返回的数据时间:60000毫秒connection.setReadTimeout(60000);// 发送请求connection.connect();// 通过connection连接,获取输⼊流if (connection.getResponseCode() == 200) {is = connection.getInputStream();// 封装输⼊流is,并指定字符集br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 存放数据StringBuffer sbf = new StringBuffer();String temp = null;while ((temp = br.readLine()) != null) {sbf.append(temp);sbf.append("\r\n");}result = sbf.toString();}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭资源if (null != br) {try {br.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}connection.disconnect();// 关闭远程连接}return result;}/*** 向指定 URL 发送POST⽅法的请求** @param httpUrl* 发送请求的 URL* @param param* 请求参数应该是{"key":"==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6qNbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"}的形式 * @return所代表远程资源的响应结果*/public static String doPost(String httpUrl, String param) {HttpURLConnection connection = null;InputStream is = null;OutputStream os = null;BufferedReader br = null;String result = null;try {URL url = new URL(httpUrl);// 通过远程url连接对象打开连接connection = (HttpURLConnection) url.openConnection();// 设置连接请求⽅式connection.setRequestMethod("POST");// 设置连接主机服务器超时时间:15000毫秒connection.setConnectTimeout(15000);// 设置读取主机服务器返回数据超时时间:60000毫秒connection.setReadTimeout(60000);// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为trueconnection.setDoOutput(true);// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可⽆connection.setDoInput(true);// 设置传⼊参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
Java调用HttpHttps接口(4)--HttpClient调用HttpHttps接口
Java调⽤HttpHttps接⼝(4)--HttpClient调⽤HttpHttps接⼝HttpClient是Apache HttpComponents项⽬下的⼀个组件,是Commons-HttpClient的升级版,两者api调⽤写法也很类似。
⽂中所使⽤到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。
1、服务端参见2、调⽤Http接⼝2.1、GET请求public static void get() {String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李⽩";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet get = new HttpGet(requestPath);CloseableHttpResponse response = httpClient.execute(get);System.out.println("GET返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("GET fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.2、POST请求(发送键值对数据)public static void post() {String requestPath = "http://localhost:8080/demo/httptest/getUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);List<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("userId", "1000"));list.add(new BasicNameValuePair("userName", "李⽩"));post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyForm(Form.form().add("userId", "1000").add("userName", "李⽩").build(), Charset.forName("utf-8")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.3、POST请求(发送JSON数据)public static void post2() {String requestPath = "http://localhost:8080/demo/httptest/addUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);post.setHeader("Content-type", "application/json");String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";post.setEntity(new StringEntity(param, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST json返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).addHeader("Content-type", "application/json").bodyString(param, ContentType.APPLICATION_JSON).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST json fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.4、上传⽂件public static void upload() {String requestPath = "http://localhost:8080/demo/httptest/upload";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");post.setEntity(new InputStreamEntity(fileInputStream));CloseableHttpResponse response = httpClient.execute(post);System.out.println("upload返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyStream(new FileInputStream("d:/a.jpg")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("upload fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.5、上传⽂件及发送键值对数据public static void multi() {String requestPath = "http://localhost:8080/demo/httptest/multi";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileBody file = new FileBody(new File("d:/a.jpg"));HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build();post.setEntity(requestEntity);CloseableHttpResponse response = httpClient.execute(post);System.out.println("multi返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).body(MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build()).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("multi fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.6、完整例⼦package com.inspur.demo.http.client;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import ValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.fluent.Form;import org.apache.http.client.fluent.Request;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.InputStreamEntity;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;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;/*** 通过HttpClient调⽤Http接⼝*/public class HttpClientCase {/*** GET请求*/public static void get() {String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李⽩";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet get = new HttpGet(requestPath);CloseableHttpResponse response = httpClient.execute(get);System.out.println("GET返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("GET fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** POST请求(发送键值对数据)*/public static void post() {String requestPath = "http://localhost:8080/demo/httptest/getUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);List<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("userId", "1000"));list.add(new BasicNameValuePair("userName", "李⽩"));post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyForm(Form.form().add("userId", "1000").add("userName", "李⽩").build(), Charset.forName("utf-8")) .execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** POST请求(发送json数据)*/public static void post2() {String requestPath = "http://localhost:8080/demo/httptest/addUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);post.setHeader("Content-type", "application/json");String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";post.setEntity(new StringEntity(param, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST json返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).addHeader("Content-type", "application/json").bodyString(param, ContentType.APPLICATION_JSON).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST json fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** 上传⽂件*/public static void upload() {String requestPath = "http://localhost:8080/demo/httptest/upload";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");post.setEntity(new InputStreamEntity(fileInputStream));CloseableHttpResponse response = httpClient.execute(post);System.out.println("upload返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyStream(new FileInputStream("d:/a.jpg")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("upload fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** 上传⽂件及发送键值对数据*/public static void multi() {String requestPath = "http://localhost:8080/demo/httptest/multi";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileBody file = new FileBody(new File("d:/a.jpg"));HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build();post.setEntity(requestEntity);CloseableHttpResponse response = httpClient.execute(post);System.out.println("multi返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).body(MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))).build()).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("multi fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}private static void close(CloseableHttpClient httpClient) {try {if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {get();post();post2();upload();multi();}}View Code3、调⽤Https接⼝与调⽤Http接⼝不⼀样的部分主要在设置ssl部分,其ssl的设置与HttpsURLConnection很相似(参见);下⾯⽤GET请求来演⽰ssl的设置,其他调⽤⽅式类似。
java模拟httphttpspost请求
java模拟httphttpspost请求1.Post请求失败的代码try {HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();result = EntityUtils.toString(entity, "UTF-8");Util.log("API,POST回来的数据是:");Util.log(result);} catch (ConnectionPoolTimeoutException e) {log.e("http get throw ConnectionPoolTimeoutException(wait time out)");} catch (ConnectTimeoutException e) {log.e("http get throw ConnectTimeoutException");} catch (SocketTimeoutException e) {log.e("http get throw SocketTimeoutException");} catch (Exception e) {log.e("http get throw Exception");} finally {httpPost.abort();}之前每次代码执⾏到上述代码的第⼆⾏的时候,会等⼀段时间然后会捕获到Exception异常。
2.分析问题当然捕获的Exception这个异常太⼤了我们不便于分析,我们查看⼀下httpClient.execute(HttpUriRequest uri)的⽅法;发下这个⽅法会抛出IOException, ClientProtocolException这两个异常,但是在调⽤⽅法的时候并没有明确捕获他们两个。
JAVA模拟HTTPpost请求上传文件
JAVA模拟HTTPpost请求上传⽂件在开发中,我们使⽤的⽐较多的HTTP请求⽅式基本上就是GET、POST。
其中GET⽤于从服务器获取数据,POST主要⽤于向服务器提交⼀些表单数据,例如⽂件上传等。
⽽我们在使⽤HTTP请求时中遇到的⽐较⿇烦的事情就是构造⽂件上传的HTTP报⽂格式,这个格式虽说也⽐较简单,但也⽐较容易出错。
今天我们就⼀起来学习HTTP POST的报⽂格式以及通过来模拟⽂件上传的请求。
⾸先我们来看⼀个POST的报⽂请求,然后我们再来详细的分析它。
POST报⽂格式POST /api/feed/ HTTP/1.1Accept-Encoding: gzipContent-Length: 225873Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBpHost: Connection: Keep-Alive--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBpContent-Disposition: form-data; name="lng"Content-Type: text/plain; charset=UTF-8Content-Transfer-Encoding: 8bit116.361545--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBpContent-Disposition: form-data; name="lat"Content-Type: text/plain; charset=UTF-8Content-Transfer-Encoding: 8bit39.979006--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBpContent-Disposition: form-data; name="images"; filename="/storage/emulated/0/Camera/jdimage/1xh0e3yyfmpr2e35tdowbavrx.jpg"Content-Type: application/octet-streamContent-Transfer-Encoding: binary这⾥是图⽚的⼆进制数据--OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp--这⾥我们提交的是经度、纬度和⼀张图⽚(图⽚数据⽐较长,⽽且⽐较杂乱,这⾥省略掉了)。
java 通用请求头写法 -回复
java 通用请求头写法-回复Java通用请求头写法在Java开发中,我们经常需要发送HTTP请求到服务器端,并且在请求中设置一些通用的请求头。
通用的请求头可以包括用户身份验证、接受的数据格式、用户代理信息等。
本文将一步一步回答关于Java通用请求头写法的问题。
第一步:导入依赖在Java中,我们可以使用Apache HttpClient库来发送HTTP请求,并且设置请求头。
首先,我们需要在项目的构建文件中添加HttpClient 的依赖。
如果你正在使用Maven构建你的项目,可以在pom.xml文件中添加以下内容:xml<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version></dependency>如果你正在使用Gradle构建你的项目,可以在build.gradle文件中添加以下内容:groovyimplementation 'org.apache.httpcomponents:httpclient:4.5.13' 第二步:创建HttpClient实例在发送HTTP请求之前,我们首先需要创建一个HttpClient的实例。
HttpClient是Apache HttpClient库中的核心类,它用于执行HTTP请求。
下面是创建HttpClient实例的代码:javaCloseableHttpClient httpClient =HttpClientBuilder.create().build();第三步:创建Http请求在创建HttpClient实例之后,我们可以使用HttpClient的实例来创建一个Http请求。
Java发送get及post请求工具方法
Java发送get及post请求⼯具⽅法import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .URL;import .URLConnection;import java.util.List;import java.util.Map;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 的形式。
Java发送httpgetpost请求,调用接口方法
Java发送httpgetpost请求,调⽤接⼝⽅法由于项⽬中要⽤,所以找了⼀些资料,整理下来。
例1:使⽤ HttpClient (commons-httpclient-3.0.jar1import java.io.ByteArrayInputStream;2import java.io.ByteArrayOutputStream;3import java.io.IOException;4import java.io.InputStream;56import mons.httpclient.HttpClient;7import mons.httpclient.methods.InputStreamRequestEntity;8import mons.httpclient.methods.PostMethod;9import mons.httpclient.methods.RequestEntity;1011public class HttpTool {1213/**14 * 发送post请求15 *16 * @param params17 * 参数18 * @param requestUrl19 * 请求地址20 * @param authorization21 * 授权书22 * @return返回结果23 * @throws IOException24*/25public static String sendPost(String params, String requestUrl,26 String authorization) throws IOException {2728byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为⼆进制流29 HttpClient httpClient = new HttpClient();// 客户端实例化30 PostMethod postMethod = new PostMethod(requestUrl);31//设置请求头Authorization32 postMethod.setRequestHeader("Authorization", "Basic " + authorization);33// 设置请求头 Content-Type34 postMethod.setRequestHeader("Content-Type", "application/json");35 InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,36 requestBytes.length);37 RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,38 requestBytes.length, "application/json; charset=utf-8"); // 请求体39 postMethod.setRequestEntity(requestEntity);40 httpClient.executeMethod(postMethod);// 执⾏请求41 InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流42byte[] datas = null;43try {44 datas = readInputStream(soapResponseStream);// 从输⼊流中读取数据45 } catch (Exception e) {46 e.printStackTrace();47 }48 String result = new String(datas, "UTF-8");// 将⼆进制流转为String49// 打印返回结果50// System.out.println(result);5152return result;5354 }5556/**57 * 从输⼊流中读取数据58 *59 * @param inStream60 * @return61 * @throws Exception62*/63public static byte[] readInputStream(InputStream inStream) throws Exception {64 ByteArrayOutputStream outStream = new ByteArrayOutputStream();65byte[] buffer = new byte[1024];66int len = 0;67while ((len = inStream.read(buffer)) != -1) {68 outStream.write(buffer, 0, len);69 }70byte[] data = outStream.toByteArray();71 outStream.close();72 inStream.close();73return data;74 }75 }例2:1import java.io.BufferedReader;2import java.io.IOException;3import java.io.InputStream;4import java.io.InputStreamReader;5import java.io.OutputStreamWriter;6import java.io.UnsupportedEncodingException;7import .HttpURLConnection;8import .InetSocketAddress;9import .Proxy;10import .URL;11import .URLConnection;12import java.util.List;13import java.util.Map;1415/**16 * Http请求⼯具类17*/18public class HttpRequestUtil {19static boolean proxySet = false;20static String proxyHost = "127.0.0.1";21static int proxyPort = 8087;22/**23 * 编码24 * @param source25 * @return26*/27public static String urlEncode(String source,String encode) {28 String result = source;29try {30 result = .URLEncoder.encode(source,encode);31 } catch (UnsupportedEncodingException e) {32 e.printStackTrace();33return "0";34 }35return result;36 }37public static String urlEncodeGBK(String source) {38 String result = source;39try {40 result = .URLEncoder.encode(source,"GBK");41 } catch (UnsupportedEncodingException e) {42 e.printStackTrace();43return "0";44 }45return result;46 }47/**48 * 发起http请求获取返回结果49 * @param req_url 请求地址50 * @return51*/52public static String httpRequest(String req_url) {53 StringBuffer buffer = new StringBuffer();54try {55 URL url = new URL(req_url);56 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();5758 httpUrlConn.setDoOutput(false);59 httpUrlConn.setDoInput(true);60 httpUrlConn.setUseCaches(false);6162 httpUrlConn.setRequestMethod("GET");63 httpUrlConn.connect();6465// 将返回的输⼊流转换成字符串66 InputStream inputStream = httpUrlConn.getInputStream();67 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");68 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);6970 String str = null;71while ((str = bufferedReader.readLine()) != null) {72 buffer.append(str);73 }74 bufferedReader.close();75 inputStreamReader.close();76// 释放资源77 inputStream.close();78 inputStream = null;79 httpUrlConn.disconnect();8081 } catch (Exception e) {82 System.out.println(e.getStackTrace());83 }84return buffer.toString();85 }8687/**88 * 发送http请求取得返回的输⼊流89 * @param requestUrl 请求地址90 * @return InputStream91*/92public static InputStream httpRequestIO(String requestUrl) {93 InputStream inputStream = null;94try {95 URL url = new URL(requestUrl);96 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();97 httpUrlConn.setDoInput(true);98 httpUrlConn.setRequestMethod("GET");99 httpUrlConn.connect();100// 获得返回的输⼊流101 inputStream = httpUrlConn.getInputStream();102 } catch (Exception e) {103 e.printStackTrace();104 }105return inputStream;106 }107108109/**110 * 向指定URL发送GET⽅法的请求111 *112 * @param url113 * 发送请求的URL114 * @param param115 * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
Java发送http请求(get、post)的示例
Java发送http请求(get、post)的⽰例1.情景展⽰ java发送get请求、post请求(form表单、json数据)⾄另⼀服务器; 可设置HTTP请求头部信息,可以接收服务器返回cookie信息,可以上传⽂件等;2.代码实现所需jar包:httpcore-4.4.1.jar;httpclient-4.4.1.jar;httpmime-4.4.1.jar;epoint-utils-9.3.3.jarimport java.io.File;import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import java.security.GeneralSecurityException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import .ssl.HostnameVerifier;import .ssl.SSLContext;import .ssl.SSLSession;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import ValuePair;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.HttpDelete;import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPatch;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.util.EntityUtils;import com.epoint.core.utils.string.StringUtil;/*** HttpClient⼯具类,使⽤http-client包实现,原先的common-httpclient已经淘汰** @作者 ko* @version [版本号, 2017年10⽉18⽇]*/public class HttpUtil{private static PoolingHttpClientConnectionManager connMgr;private static RequestConfig requestConfig;private static final int MAX_TIMEOUT = 7000;/*** 直接以流返回*/public static final int RTN_TYPE_1 = 1;/*** 直接以string返回*/public static final int RTN_TYPE_2 = 2;/*** 以map返回,reslut:接⼝结果string;statusCode:http状态码*/public static final int RTN_TYPE_3 = 3;/*** 以map返回,reslut:接⼝结果string;statusCode:http状态码;cookie:response的cookie * cookie值键值对,格式 key1=value1;key2=value2;...*/public static final int RTN_TYPE_4 = 4;/*** 默认上传⽂件的⽂件流或file 的key Name*/private static final String DEFAULT_BINARYBODY_KEYNAME = "file";static {// 设置连接池connMgr = new PoolingHttpClientConnectionManager();// 设置连接池⼤⼩connMgr.setMaxTotal(100);connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());// 在提交请求之前测试连接是否可⽤connMgr.setValidateAfterInactivity(1);RequestConfig.Builder configBuilder = RequestConfig.custom();// 设置连接超时configBuilder.setConnectTimeout(MAX_TIMEOUT);// 设置读取超时configBuilder.setSocketTimeout(MAX_TIMEOUT);// 设置从连接池获取连接实例的超时configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);requestConfig = configBuilder.build();}/*** 发送 GET请求** @param apiUrl* API接⼝URL* @return String 响应内容*/public static String doGet(String apiUrl) {return doHttp(apiUrl, null, "get", RTN_TYPE_2);}/*** 发送POST请求** @param apiUrl* API接⼝URL* @param params* K-V参数* @return String 响应内容*/public static String doPost(String apiUrl, Map<String, Object> params) {return doHttp(apiUrl, params, "post", RTN_TYPE_2);}/*** 发送POST请求** @param apiUrl* API接⼝URL* @param json* json参数* @return String 响应内容*/public static String doPostJson(String apiUrl, String json) {return doHttp(apiUrl, json, "post", RTN_TYPE_2);}/*** 发送 http 请求** @param apiUrl* API接⼝URL* @param params* {Map<String, Object> K-V形式、json字符串}* @param method* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}* @param type* {HttpUtil.RTN_TYPE_1:请求返回stream(此时流需要在外部⼿动关闭);HttpUtil.* RTN_TYPE_2:string;HttpUtil.RTN_TYPE_3:返回⼀个map,map包含结果(* 结果是string形式)以及http状态码;HttpUtil.RTN_TYPE_4:返回⼀个map,map包含结果(* 结果是string形式), http状态码和cookie;其他情况返回string}* 如果结果是个map,key为:result,statusCode,cookie,分别返回结果* string,http状态码,cookie; cookie值键值对,格式* key1=value1;key2=value2;...* @return stream或 string 或 map*/public static <T> T doHttp(String apiUrl, Object params, String method, int type) {return doHttp(apiUrl, null, params, method, type);}/*** 发送 http 请求** @param apiUrl* API接⼝URL* @param headerMap* header信息Map<String, String>,可设置cookie* @param params* {Map<String, Object> K-V形式、json字符串}* @param method* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}* @param type* {HttpUtil.RTN_TYPE_1:请求返回stream(此时流需要在外部⼿动关闭);HttpUtil.* RTN_TYPE_2:string;HttpUtil.RTN_TYPE_3:返回⼀个map,map包含结果(* 结果是string形式)以及http状态码;HttpUtil.RTN_TYPE_4:返回⼀个map,map包含结果(* 结果是string形式), http状态码和cookie;其他情况返回string}* 如果结果是个map,key为:result,statusCode,cookie,分别返回结果* string,http状态码,cookie; cookie值键值对,格式* key1=value1;key2=value2;...* @return stream或 string 或 map*/public static <T> T doHttp(String apiUrl, Map<String, String> headerMap, Object params, String method, int type) { CloseableHttpClient httpClient = null;if (isSSL(apiUrl)) {httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();}else {httpClient = HttpClients.createDefault();}return doHttp(httpClient, apiUrl, headerMap, params, method, type);}/*** 发送 http 请求** @param httpClient* httpclient对象由外部传⼊,⽤户需要保持登录状态等情况此时如果要ssl,那么要在外部加⼊ssl特性* httpClient =* HttpClients.custom().setSSLSocketFactory(HttpUtil.* createSSLConnSocketFactory())* .setConnectionManager(HttpUtil.getConnMgr()).* setDefaultRequestConfig(HttpUtil..getRequestConfig()).build();* @param apiUrl* API接⼝URL* @param headerMap* header信息Map<String, String>,可设置cookie** @param params* {Map<String, Object> K-V形式、json字符串}* @param method* {null、或者post:POST请求、patch:PATCH请求、delete:DELETE请求、get:GET请求}* @param type* {HttpUtil.RTN_TYPE_1:请求返回stream(此时流需要在外部⼿动关闭);HttpUtil.* RTN_TYPE_2:string;HttpUtil.RTN_TYPE_3:返回⼀个map,map包含结果(* 结果是string形式)以及http状态码;HttpUtil.RTN_TYPE_4:返回⼀个map,map包含结果(* 结果是string形式), http状态码和cookie;其他情况返回string}* 如果结果是个map,key为:result,statusCode,cookie,分别返回结果* string,http状态码,cookie; cookie值键值对,格式* key1=value1;key2=value2;...* @return stream或 string 或 map*/@SuppressWarnings("unchecked")public static <T> T doHttp(CloseableHttpClient httpClient, String apiUrl, Map<String, String> headerMap, Object params, String method, int type) {HttpRequestBase httpPost = null;if (StringUtil.isNotBlank(method)) {if ("patch".equalsIgnoreCase(method)) {httpPost = new HttpPatch(apiUrl);}else if ("delete".equalsIgnoreCase(method)) {httpPost = new HttpDelete(apiUrl);}else if ("get".equalsIgnoreCase(method)) {httpPost = new HttpGet(apiUrl);}else if ("post".equalsIgnoreCase(method)) {httpPost = new HttpPost(apiUrl);}}else {httpPost = new HttpPost(apiUrl);}CloseableHttpResponse response = null;try {// 设置header信息if (headerMap != null && !headerMap.isEmpty()) {for (Map.Entry<String, String> entry : headerMap.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}if (isSSL(apiUrl)) {httpPost.setConfig(requestConfig);}// 参数不为null、要处理参数if (params != null) {// get请求拼接在url后⾯if (httpPost instanceof HttpGet) {StringBuffer param = new StringBuffer();if (params instanceof Map) {Map<String, Object> paramsConvert = (Map<String, Object>) params;int i = 0;for (String key : paramsConvert.keySet()) {if (i == 0)param.append("?");elseparam.append("&");param.append(key).append("=").append(paramsConvert.get(key));i++;}}else {param.append("?" + params.toString());}apiUrl += param;}// delete请求暂不处理else if (!(httpPost instanceof HttpDelete)) {// K-V形式if (params instanceof Map) {Map<String, Object> paramsConvert = (Map<String, Object>) params;List<NameValuePair> pairList = new ArrayList<>(paramsConvert.size());for (Map.Entry<String, Object> entry : paramsConvert.entrySet()) {NameValuePair pair = new BasicNameValuePair(entry.getKey(),entry.getValue() == null ? "" : entry.getValue().toString());pairList.add(pair);}((HttpEntityEnclosingRequestBase) httpPost).setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));}// json格式else {StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");stringEntity.setContentEncoding("UTF-8");stringEntity.setContentType("application/json");((HttpEntityEnclosingRequestBase) httpPost).setEntity(stringEntity);}}}response = httpClient.execute(httpPost);// int statusCode = response.getStatusLine().getStatusCode();// if (statusCode != HttpStatus.SC_OK) {// return null;// }HttpEntity entity = response.getEntity();if (entity != null) {if (type == RTN_TYPE_1) {return (T) entity.getContent();}else if (RTN_TYPE_2 == type) {return (T) EntityUtils.toString(entity, "UTF-8");}else if (RTN_TYPE_3 == type || RTN_TYPE_4 == type) {Map<String, String> rtnMap = new HashMap<String, String>();rtnMap.put("result", EntityUtils.toString(entity, "UTF-8"));rtnMap.put("statusCode", response.getStatusLine().getStatusCode() + "");if (RTN_TYPE_4 == type) {rtnMap.put("cookie", getCookie(response));}return (T) rtnMap;}else {return (T) EntityUtils.toString(entity, "UTF-8");}}}catch (Exception e) {e.printStackTrace();}finally {if (response != null && type != RTN_TYPE_1) {try {EntityUtils.consume(response.getEntity());}catch (IOException e) {e.printStackTrace();}}}return null;}/*** 上传附件(post形式)** @param url* 请求地址* @param headerMap* header参数map Map<String, String>* @param paramMap* 额外的参数map,Map<String, String>* @param file* 可以选择本地⽂件上传;如果传了file,⼜传了fileName,那么⽂件名以fileName为准,否则是file的⽂件名 * @param fileName* 以流传输时,必须指定⽂件名* @param ssl* 是否需要ssl* @return result,返回上传结果,如果接⼝没有返回值,则为状态码*/public static String upload(String url, Map<String, String> headerMap, Map<String, String> paramMap, File file,String fileName, boolean ssl) {return upload(url, headerMap, paramMap, file, null, fileName, ssl);}/*** 上传附件(post形式)** @param url* 请求地址* @param headerMap* header参数map Map<String, String>* @param paramMap* 额外的参数map,Map<String, String>* @param in* ⽂件流* @param fileName* 以流传输时,必须指定⽂件名* @param ssl* 是否需要ssl* @return result,返回上传结果,如果接⼝没有返回值,则为状态码*/public static String upload(String url, Map<String, String> headerMap, Map<String, String> paramMap, InputStream in, String fileName, boolean ssl) {return upload(url, headerMap, paramMap, null, in, fileName, ssl);}/*** 上传附件(post形式)** @param httpClient* 外部传⼊httpClient* @param url* 请求地址* @param headerMap* header参数map Map<String, String>* @param paramMap* 额外的参数map,Map<String, String>* @param file* 可以选择本地⽂件上传;如果传了file,⼜传了fileName,那么⽂件名以fileName为准,否则是file的⽂件名* @param fileName* 以流传输时,必须指定⽂件名* @param ssl* 是否需要ssl* @return result,返回上传结果,如果接⼝没有返回值,则为状态码*/public static String upload(CloseableHttpClient httpClient, String url, Map<String, String> headerMap,Map<String, String> paramMap, File file, String fileName, boolean ssl) {return upload(httpClient, url, headerMap, paramMap, file, null, fileName, ssl);}/*** 上传附件(post形式)** @param httpClient* 外部传⼊httpClient* @param url* 请求地址* @param headerMap* header参数map Map<String, String>* @param paramMap* 额外的参数map,Map<String, String>* @param in* ⽂件流* @param fileName* 以流传输时,必须指定⽂件名* @param ssl* 是否需要ssl* @return result,返回上传结果,如果接⼝没有返回值,则为状态码*/public static String upload(CloseableHttpClient httpClient, String url, Map<String, String> headerMap,Map<String, String> paramMap, InputStream in, String fileName, boolean ssl) {return upload(httpClient, url, headerMap, paramMap, null, in, fileName, ssl);}/*** 上传附件(post形式)** @param url* 请求地址* @param headerMap* header参数map Map<String, String>* @param paramMap* 额外的参数map,Map<String, String>* @param file* 可以选择本地⽂件上传,file,in互斥;如果传了file,⼜传了fileName,那么⽂件名以fileName为准,否则* 是file的⽂件名* @param in* ⽂件流* @param fileName* 以流传输时,必须指定⽂件名* @param ssl* 是否需要ssl* @return result,返回上传结果,如果接⼝没有返回值,则为状态码*/private static String upload(String url, Map<String, String> headerMap, Map<String, String> paramMap, File file,InputStream in, String fileName, boolean ssl) {CloseableHttpClient httpClient = null;if (ssl) {httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();}else {httpClient = HttpClients.createDefault();}return upload(httpClient, url, headerMap, paramMap, file, in, fileName, ssl);}/*** 上传附件(post形式)** @param httpClient* 外部传⼊httpClient* @param url* 请求地址* @param headerMap* header参数map Map<String, String>* @param paramMap* 额外的参数map,Map<String, String>* @param file* 可以选择本地⽂件上传,file,in互斥;如果传了file,⼜传了fileName,那么⽂件名以fileName为准,否则* 是file的⽂件名* @param in* ⽂件流* @param fileName* 以流传输时,必须指定⽂件名* @param ssl* 是否需要ssl* @return result,返回上传结果,如果接⼝没有返回值,则为状态码*/private static String upload(CloseableHttpClient httpClient, String url, Map<String, String> headerMap,Map<String, String> paramMap, File file, InputStream in, String fileName, boolean ssl) {String result = "";CloseableHttpResponse response = null;try {HttpPost httpPost = new HttpPost(url);// 设置header信息if (headerMap != null && !headerMap.isEmpty()) {for (Map.Entry<String, String> entry : headerMap.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}if (ssl) {httpPost.setConfig(requestConfig);}MultipartEntityBuilder builder = MultipartEntityBuilder.create();// 选择以file形式上传if (file != null && file.exists()) {if (StringUtil.isNotBlank(fileName)) {builder.addBinaryBody(DEFAULT_BINARYBODY_KEYNAME, file, ContentType.DEFAULT_BINARY, fileName); }else {builder.addBinaryBody(DEFAULT_BINARYBODY_KEYNAME, file);}}// 以流上传else if (in != null && StringUtil.isNotBlank(fileName)) {builder.addBinaryBody(DEFAULT_BINARYBODY_KEYNAME, in, ContentType.DEFAULT_BINARY, fileName);}if (paramMap != null && !paramMap.isEmpty()) {for (Map.Entry<String, String> entry : paramMap.entrySet()) {builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN));}}HttpEntity reqEntity = builder.build();httpPost.setEntity(reqEntity);response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if (entity != null) {result = EntityUtils.toString(entity, "UTF-8");}else {result = response.getStatusLine().getStatusCode() + "";}}catch (Exception e) {e.printStackTrace();}finally {if (response != null) {try {EntityUtils.consume(response.getEntity());}catch (IOException e) {e.printStackTrace();}}}return result;}private static String getCookie(HttpResponse httpResponse) {Map<String, String> cookieMap = new HashMap<String, String>(64);Header headers[] = httpResponse.getHeaders("Set-Cookie");if (headers == null || headers.length == 0) {return null;}String cookie = "";for (int i = 0; i < headers.length; i++) {cookie += headers[i].getValue();if (i != headers.length - 1) {cookie += ";";}}String cookies[] = cookie.split(";");for (String c : cookies) {c = c.trim();if (cookieMap.containsKey(c.split("=")[0])) {cookieMap.remove(c.split("=")[0]);}cookieMap.put(c.split("=")[0],c.split("=").length == 1 ? "" : (c.split("=").length == 2 ? c.split("=")[1] : c.split("=", 2)[1]));}String cookiesTmp = "";for (String key : cookieMap.keySet()) {cookiesTmp += key + "=" + cookieMap.get(key) + ";";}return cookiesTmp.substring(0, cookiesTmp.length() - 2);}/*** 创建SSL安全连接** @return*/public static SSLConnectionSocketFactory createSSLConnSocketFactory() {SSLConnectionSocketFactory sslsf = null;try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true;}}).build();sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier(){@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}});}catch (GeneralSecurityException e) {e.printStackTrace();}return sslsf;}public static PoolingHttpClientConnectionManager getConnMgr() {return connMgr;}public static RequestConfig getRequestConfig() {return requestConfig;}private static boolean isSSL(String apiUrl) {if (apiUrl.indexOf("https") != -1 ) {return true;}else {return false;}}}以上就是Java 发送http请求(get、post)的⽰例的详细内容,更多关于Java 发送http请求的资料请关注其它相关⽂章!。
HttpUtil工具类,发送GetPost请求,支持Http和Https协议
HttpUtil⼯具类,发送GetPost请求,⽀持Http和Https协议HttpUtil⼯具类,发送Get/Post请求,⽀持Http和Https协议使⽤⽤Httpclient封装的HttpUtil⼯具类,发送Get/Post请求1. maven引⼊httpclient依赖<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.12</version></dependency>2. GET请求public static String doGet(String path, Map<String, String> param, Map<String, String> headers) {HttpGet httpGet = null;CloseableHttpResponse response = null;CloseableHttpClient httpClient = wrapClient(path);// 创建uriURIBuilder builder = null;try {builder = new URIBuilder(path);if (param != null) {for (String key : param.keySet()) {builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 创建http GET请求httpGet = new HttpGet(uri);if (headers != null && headers.size() > 0) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpGet.addHeader(entry.getKey(), entry.getValue());}}// 执⾏请求response = httpClient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {return EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {throw new RuntimeException("[发送Get请求错误:]" + e.getMessage());} finally {try {httpGet.releaseConnection();response.close();if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return null;}3. POST请求public static String doPostJson(String url, String jsonParam, Map<String, String> headers) {HttpPost httpPost = null;CloseableHttpResponse response = null;CloseableHttpClient httpClient = wrapClient(url);try {httpPost = new HttpPost(url);//addHeader,如果Header没有定义则添加,已定义则不变,setHeader会重新赋值httpPost.addHeader("Content-type","application/json;charset=utf-8");httpPost.setHeader("Accept", "application/json");StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);// entity.setContentType("text/json");// entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));httpPost.setEntity(entity);//是否有headerif (headers != null && headers.size() > 0) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 执⾏请求response = httpClient.execute(httpPost);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {return EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {throw new RuntimeException("[发送POST请求错误:]" + e.getMessage());} finally {try {httpPost.releaseConnection();response.close();if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return null;}3. 获取httpclient的⽅法这⾥会根据url⾃动匹配需要的是http的还是https的clientprivate static CloseableHttpClient wrapClient(String url) {CloseableHttpClient client = HttpClientBuilder.create().build();if (url.startsWith("https")) {client = getCloseableHttpsClients();}return client;}4. 对于https的需要⾃⼰实现⼀下clientprivate static CloseableHttpClient getCloseableHttpsClients() {// 采⽤绕过验证的⽅式处理https请求SSLContext sslcontext = createIgnoreVerifySSL();// 设置协议http和https对应的处理socket链接⼯⼚的对象Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager);// 创建⾃定义的httpsclient对象CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();return client;}private static SSLContext createIgnoreVerifySSL() {// 创建套接字对象SSLContext sslContext = null;try {//指定TLS版本sslContext = SSLContext.getInstance("TLSv1.2");} catch (NoSuchAlgorithmException e) {throw new RuntimeException("[创建套接字失败:] " + e.getMessage());}// 实现X509TrustManager接⼝,⽤于绕过验证X509TrustManager trustManager = new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,String paramString) throws CertificateException {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,String paramString) throws CertificateException {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}};try {//初始化sslContext对象sslContext.init(null, new TrustManager[]{trustManager}, null);} catch (KeyManagementException e) {throw new RuntimeException("[初始化套接字失败:] " + e.getMessage()); }return sslContext;}以上全部都测试通过,如果有错误,欢迎⼤佬们指出,感谢备注:完整版的让坚持成为品质,让优秀成为习惯!加油!。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
一般的情况下我们都是使用IE或者Navigator浏览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据等等。
所访问的这些页面有的仅仅是一些普通的页面,有的需要用户登录后方可使用,或者需要认证以及是一些通过加密方式传输,例如HTTPS。
目前我们使用的浏览器处理这些情况都不会构成问题。
不过你可能在某些时候需要通过程序来访问这样的一些页面,比如从别人的网页中“偷”一些数据;利用某些站点提供的页面来完成某种功能,例如说我们想知道某个手机号码的归属地而我们自己又没有这样的数据,因此只好借助其他公司已有的网站来完成这个功能,这个时候我们需要向网页提交手机号码并从返回的页面中解析出我们想要的数据来。
如果对方仅仅是一个很简单的页面,那我们的程序会很简单,本文也就没有必要大张旗鼓的在这里浪费口舌。
但是考虑到一些服务授权的问题,很多公司提供的页面往往并不是可以通过一个简单的URL就可以访问的,而必须经过注册然后登录后方可使用提供服务的页面,这个时候就涉及到COOKIE问题的处理。
我们知道目前流行的动态网页技术例如ASP、JSP无不是通过COOKIE来处理会话信息的。
为了使我们的程序能使用别人所提供的服务页面,就要求程序首先登录后再访问服务页面,这过程就需要自行处理cookie,想想当你用.HttpURLConnection来完成这些功能时是多么恐怖的事情啊!况且这仅仅是我们所说的顽固的WEB服务器中的一个很常见的“顽固”!再有如通过HTTP来上传文件呢?不需要头疼,这些问题有了“它”就很容易解决了!我们不可能列举所有可能的顽固,我们会针对几种最常见的问题进行处理。
当然了,正如前面说到的,如果我们自己使用.HttpURLConnection来搞定这些问题是很恐怖的事情,因此在开始之前我们先要介绍一下一个开放源码的项目,这个项目就是Apache开源组织中的httpclient,它隶属于Jakarta的commons项目,目前的版本是2.0RC2。
commons下本来已经有一个net的子项目,但是又把httpclient单独提出来,可见http 服务器的访问绝非易事。
Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。
通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS 的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给httpclient替你完成。
本文会针对我们在编写HTTP客户端程序时经常碰到的几个问题进行分别介绍如何使用httpclient来解决它们,为了让读者更快的熟悉这个项目我们最开始先给出一个简单的例子来读取一个网页的内容,然后循序渐进解决掉前进中的所有问题。
1.读取网页(HTTP/HTTPS)内容下面是我们给出的一个简单的例子用来访问某个页面/** Created on 2003-12-14 by Liudong*/package http.demo;import java.io.IOException;import mons.httpclient.*;import mons.httpclient.methods.*;/*** 最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面* @author Liudongpublic class SimpleClient {public static void main(String[] args) throws IOException{HttpClient client = new HttpClient();//设置代理服务器地址和端口//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);//使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的h ttp换成httpsHttpMethod method = new GetMethod("";);//使用POST方法//HttpMethod method = new PostMethod("";);client.executeMethod(method);//打印服务器返回的状态System.out.println(method.getStatusLine());//打印返回的信息System.out.println(method.getResponseBodyAsString());//释放连接method.releaseConnection();}}在这个例子中首先创建一个HTTP客户端(HttpClient)的实例,然后选择提交的方法是GET 或者POST,最后在HttpClient实例上执行提交的方法,最后从所选择的提交方法中读取服务器反馈回来的结果。
这就是使用HttpClient的基本流程。
其实用一行代码也就可以搞定整个请求的过程,非常的简单!2.以GET或者POST方式向网页提交参数其实前面一个最简单的示例中我们已经介绍了如何使用GET或者POST方式来请求一个页面,本小节与之不同的是多了提交时设定页面所需的参数,我们知道如果是GET的请求方式,那么所有参数都直接放到页面的URL后面用问号与页面地址隔开,每个参数用&隔开,例如:?name=liudong&mobile=123456,但是当使用POST方法时就会稍微有一点点麻烦。
本小节的例子演示向如何查询手机号码所在的城市,代码如下:/** Created on 2003-12-7 by Liudong*/package http.demo;import java.io.IOException;import mons.httpclient.*;import mons.httpclient.methods.*;/*** 提交参数演示* 该程序连接到一个用于查询手机号码所属地的页面* 以便查询号码段1330227所在的省份以及城市* @author Liudongpublic class SimpleHttpClient {public static void main(String[] args) throws IOException{HttpClient client = new HttpClient();client.getHostConfiguration().setHost("", 80, "http ");HttpMethod method = getPostMethod();//使用POST方式提交数据client.executeMethod(method);//打印服务器返回的状态System.out.println(method.getStatusLine());//打印结果页面String response = new String(method.getResponseBodyAsString().getB ytes("8859_1"));//打印返回的信息System.out.println(response);method.releaseConnection();}/*** 使用GET方式提交数据* @return*/private static HttpMethod getGetMethod(){return new GetMethod("/simcard.php?simcard=1330227");}/*** 使用POST方式提交数据* @return*/private static HttpMethod getPostMethod(){PostMethod post = new PostMethod("/simcard.php");NameValuePair simcard = new NameValuePair("simcard","1330227");post.setRequestBody(new NameValuePair[] { simcard});return post;}}在上面的例子中页面/simcard.php需要一个参数是simcard,这个参数值为手机号码段,即手机号码的前七位,服务器会返回提交的手机号码对应的省份、城市以及其他详细信息。
GET的提交方法只需要在URL后加入参数信息,而POST则需要通过NameValuePair类来设置参数名称和它所对应的值3.处理页面重定向在JSP/Servlet编程中response.sendRedirect方法就是使用HTTP协议中的重定向机制。
它与JSP中的<jsp:forward …>的区别在于后者是在服务器中实现页面的跳转,也就是说应用容器加载了所要跳转的页面的内容并返回给客户端;而前者是返回一个状态码,这些状态码的可能值见下表,然后客户端读取需要跳转到的页面的URL并重新加载新的页面。
就是这样一个过程,所以我们编程的时候就要通过HttpMethod.getStatusCode()方法判断返回值是否为下表中的某个值来判断是否需要跳转。
如果已经确认需要进行页面跳转了,那么可以通过读取HTTP头中的location属性来获取新的地址。
状态码对应HttpServletResponse的常量详细描述301SC_MOVED_PERMANENTLY页面已经永久移到另外一个新地址302SC_MOVED_TEMPORARILY页面暂时移动到另外一个新的地址303SC_SEE_OTHER客户端请求的地址必须通过另外的URL来访问307SC_TEMPORARY_REDIRECT同SC_MOVED_TEMPORARILY下面的代码片段演示如何处理页面的重定向client.executeMethod(post);System.out.println(post.getStatusLine().toString());post.releaseConnection();//检查是否重定向int statuscode = post.getStatusCode();if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||(statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||(statuscode == HttpStatus.SC_SEE_OTHER) ||(statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)){//读取新的URL地址Header header = post.getResponseHeader("location");if (header != null) {String newuri = header.getValue();if ((newuri == null) || (newuri.equals("")))newuri = "/";GetMethod redirect = new GetMethod(newuri);client.executeMethod(redirect);System.out.println("Redirect:"+ redirect.getStatusLine().toString ());redirect.releaseConnection();} else {System.out.println("Invalid redirect");} 我们可以自行编写两个JSP页面,其中一个页面用response.sendRedirect方法重定向到另外一个页面用来测试上面的例子。