Get请求
import java.net.URLConnection; public class HttpGet { public static void main(String[] args) throws Exception { final String spec = "http://192.168.0.115:20000/test/test.json?item=123"; URL url = new URL(spec); URLConnection connection = url.openConnection(); HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setRequestProperty("Accept-Charset", "utf-8"); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (httpURLConnection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader( new InputStreamReader( httpURLConnection.getInputStream()))) { String tempLine = null; StringBuffer resultBuffer = new StringBuffer(); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } System.out.println(resultBuffer.toString()); } } } }
POST请求
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class HttpPost { public static void main(String[] args) throws Exception { final String spec = "http://192.168.0.115:20000/test/test.json"; URL url = new URL(spec); URLConnection connection = url.openConnection(); HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setRequestProperty("Accept-Charset", "utf-8"); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter( httpURLConnection.getOutputStream())) { outputStreamWriter.write("item=123"); outputStreamWriter.flush(); } Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields(); for ( Entry<String, List<String>> entry : headerFields.entrySet()) { System.out.println(entry.getKey()); for (String value : entry.getValue()) { System.out.println("\t" + value); } } if (httpURLConnection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader( new InputStreamReader( httpURLConnection.getInputStream()))) { String tempLine = null; StringBuffer resultBuffer = new StringBuffer(); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } System.out.println(resultBuffer.toString()); } } } }