java 用Java发送GET和POST请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 用Java发送GET和POST请求相关的知识,希望对你有一定的参考价值。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class HTTPRequest {
	private String url;
	final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11";

	public HTTPRequest(String url) {
		this.url = url;
	}

	public HTTPResponse get() throws IOException {
		URL obj = new URL(this.url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod(HTTPMethods.GET);
		con.setRequestProperty("User-Agent", USER_AGENT);
		int responseCode = con.getResponseCode();
		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		return new HTTPResponse(responseCode, response.toString());
	}

	public HTTPResponse post(String postParams) throws IOException {
		URL obj = new URL(this.url);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
		con.setRequestMethod(HTTPMethods.POST);
		con.setRequestProperty("User-Agent", USER_AGENT);
		String postData = postParams;
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(postData);
		wr.flush();
		wr.close();
		int responseCode = con.getResponseCode();
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuilder response = new StringBuilder();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		return new HTTPResponse(responseCode, response.toString());
	}

	public String getUrl() {
		return url;
	}
	
	/*
	* This class should be in a separate file
	*/
	
	public final class HTTPMethods{
	  public static final String GET = "GET";
	  public static final String POST = "POST";
	  public static final String PUT = "PUT";
	  public static final String DELETE = "DELETE";
	}
	
	/*
	* This class should be in a separate file
	*/
	public class HTTPResponse {
    		private int responseCode;
    		private String reponse;

    		public HTTPResponse(int responseCode, String response) {
        		this.responseCode = responseCode;
        		this.reponse = response;
    		}
    		public int getResponseCode() {
        		return responseCode;
    		}

    		public String getReponse() {
        		return reponse;
    		}
	}

}

以上是关于java 用Java发送GET和POST请求的主要内容,如果未能解决你的问题,请参考以下文章

Java GET和POST请求

Java爬虫利用GET和POST发送请求,获取服务器返回信息

Java Socket 实现HTTP与HTTPS协议发送POST/GET请求

Http (java)的post和get方式

java发送http的get和post请求

Java 后台模拟发送 POST GET 请求