如何在Java中发送HTTP请求GET/POST

时间:2020-02-23 14:34:23  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中发送HTTP GET/POST。

在需要发送HTTP GET或者POST请求时有多次。
我们可以使用HttpUrlConnection在Java中发送Get/Post请求。
它属于Java.net包。

httpurlConnection示例:

我们将发送到RESTful Web服务CRUD示例中使用的URL的GET或者POST请求,因此而不是使用PostMan,我们将使用Java发送请求。

获取URL:

http://localhost:8080/JAXRSJsonCRUDExample/rest/countries

它将在JSON格式中给我们列出的国家/地区。

发布URL:

http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Post data:{"id":5,"countryName":"USA","population":8000}

它将创建一个新的国家资源并将其添加到县的列表中。

Java代码:

package org.igi.theitroad.corejava;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @author igi Mandliya
 */
public class HttpURLConnectionExample {
 
 private final String USER_AGENT = "Mozilla/5.0";
 
 public static void main(String[] args) throws Exception {
 
  HttpURLConnectionExample http = new HttpURLConnectionExample();
 
     //Sending get request
  http.sendingGetRequest();
  
    //Sending post request
  http.sendingPostRequest();
 
 }
 
 //HTTP GET request
 private void sendingGetRequest() throws Exception {
 
  String urlString = "http://localhost:8080/JAXRSJsonCRUDExample/rest/countries";
  
  URL url = new URL(urlString);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
 
  //By default it is GET request
  con.setRequestMethod("GET");
 
  //add request header
  con.setRequestProperty("User-Agent", USER_AGENT);
 
  int responseCode = con.getResponseCode();
  System.out.println("Sending get request : "+ url);
  System.out.println("Response code : "+ responseCode);
 
  //Reading response from input Stream
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();
 
  while ((output = in.readLine()) != null) {
   response.append(output);
  }
  in.close();
 
  //printing result from response
  System.out.println(response.toString());
 
 }
 
 //HTTP Post request
 private void sendingPostRequest() throws Exception {
 
  String url = "http://localhost:8080/JAXRSJsonCRUDExample/rest/countries";
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
        //Setting basic post request
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  con.setRequestProperty("Content-Type","application/json");
 
  String postJsonData = "{"id":5,"countryName":"USA","population":8000}";
  
  //Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(postJsonData);
  wr.flush();
  wr.close();
 
  int responseCode = con.getResponseCode();
  System.out.println("nSending 'POST' request to URL : " + url);
  System.out.println("Post Data : " + postJsonData);
  System.out.println("Response Code : " + responseCode);
 
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();
 
  while ((output = in.readLine()) != null) {
   response.append(output);
  }
  in.close();
  
  //printing result from response
  System.out.println(response.toString());
 }
}

运行上面的程序时,我们将得到以下输出:

Sending get request : http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Response code : 200
[{"id":1,"countryName":"Netherlands","population":10000},{"id":2,"countryName":"Bhutan","population":7000},{"id":3,"countryName":"Nepal","population":8000},{"id":4,"countryName":"China","population":20000}]
 
Sending 'POST' request to URL : http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Post Data : {"id":5,"countryName":"USA","population":8000}
Response Code : 200
{"id":5,"countryName":"USA","population":8000}

如果你注释http.sendingpostrequest();并仅发送请求。
我们将得到以下输出:

[{"id":1,"countryName":"Netherlands","population":10000},{"id":2,"countryName":"Bhutan","population":7000},{"id":3,"countryName":"Nepal","population":8000},{"id":4,"countryName":"China","population":20000},
{"id":5,"countryName":"USA","population":8000}]

我们可以看到美国将添加到国家/地区列表中。