Java發送GET、POST請求代碼

niki 9年前發布 | 2K 次閱讀 Java

一、創建一個servlet來接收get或post請求

package guwen;

import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader;

public class TestServlet extends HttpServlet{

    /*       接收get請求      */     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         req.setCharacterEncoding("UTF-8");         resp.setCharacterEncoding("UTF-8");         System.out.println(req.getQueryString());  //打印參數         PrintWriter out = resp.getWriter();         out.print("響應");  //響應     }

    /*       接收post請求      */     @Override     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         resp.setCharacterEncoding("UTF-8");         req.setCharacterEncoding("UTF-8");         System.out.println(req.getQueryString());  //打印參數         InputStream inputStream = req.getInputStream();         SAXReader reader = new SAXReader();         try {             Document document = reader.read(inputStream);  //報文體             System.out.println(document.asXML());         } catch (DocumentException e) {             e.printStackTrace();         }         PrintWriter out = resp.getWriter();         out.print("響應");  //響應     }

     }</pre>

二、發送請求

package guwen;

import java.io.IOException;

import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; 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.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils;

public class ConnectionUtil {          public static void main(String[] args) throws ClientProtocolException, IOException {         //sent get         doGet("http://localhost:8088/sentTest/test?p=123&quot;);         //sent post         doPost("http://localhost:8088/sentTest/test?p=321","<xml><a>aa</a><b>哈</b></xml>&quot;);     }          /       發送get請求       @throws IOException       */     public static String doGet(String url) throws ClientProtocolException, IOException {                  CloseableHttpClient httpClient = HttpClientBuilder.create().build();                    HttpGet httpGet = new HttpGet(url);                 //配置請求的超時設置           RequestConfig requestConfig = RequestConfig.custom()                     .setConnectionRequestTimeout(50)                   .setConnectTimeout(50)                     .setSocketTimeout(50).build();             httpGet.setConfig(requestConfig);                       CloseableHttpResponse response = null;         String res = null;         try {             response = httpClient.execute(httpGet);   //發送請求             System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());               HttpEntity entity = response.getEntity();                       res = EntityUtils.toString(entity,"utf-8");                System.out.println(res);           } catch (ClientProtocolException e) {             throw e;         } catch (IOException e) {             throw e;         } finally{             httpGet.releaseConnection();          }                    return res;     }                    /       發送get請求       @throws IOException       */     public static String doPost(String url,String body) throws IOException {                  CloseableHttpClient httpclient = HttpClientBuilder.create().build();           HttpPost httpPost = new HttpPost(url);         //配置請求的超時設置           RequestConfig requestConfig = RequestConfig.custom()                     .setConnectionRequestTimeout(50)                   .setConnectTimeout(50)                     .setSocketTimeout(50).build();             httpPost.setConfig(requestConfig);                   CloseableHttpResponse response = null;         String res = null;         try {             if (body != null) {  //設置報文體 設置編碼為 UTF-8                 StringEntity entity = new StringEntity(body, "UTF-8");                 httpPost.setEntity(entity);             }             response = httpclient.execute(httpPost);  //發送請求             System.out.println(response.toString());                            HttpEntity entity = response.getEntity();               res = EntityUtils.toString(entity, "utf-8");               System.out.println(res);           } catch (ClientProtocolException e) {             throw e;         } catch (IOException e) {             throw e;         } finally{             httpPost.releaseConnection();         }                  return res;                       }           }</pre>


 本文由用戶 niki 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!