Java 网络请求
Posted SamNicole1809
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 网络请求相关的知识,希望对你有一定的参考价值。
直接上代码:
public class HttpUtils { private static final RestTemplate restTemplate = new RestTemplate(); // Get请求 public static String Get(String url, Map<String, Object> params) { String uri = buildUri(url, params); ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class); return response.getBody(); } // Get请求 public static String Get(String uri) { ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class); return response.getBody(); } // Post请求(JSON请求) public static String JPost(String url, Map<String, Object> params) { HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, jsonHeaderBuilder()); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); return response.getBody(); }// Post请求(Params) public static String UPost(String url, MultiValueMap<String, String> params) { HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, urlHeaderBuilder()); ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); return response.getBody(); } // 拼接Url和参数 private static String buildUri(String url, Map<String, Object> params) { StringBuilder sb = new StringBuilder(url); sb.append("?"); for (Map.Entry<String, Object> entry : params.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } // 构建Url请求头 private static HttpHeaders urlHeaderBuilder() { HttpHeaders h = new HttpHeaders(); h.setContentType(MediaType.APPLICATION_FORM_URLENCODED); return h; } // 构建Json请求头 private static HttpHeaders jsonHeaderBuilder() { HttpHeaders h = new HttpHeaders(); h.setContentType(MediaType.APPLICATION_JSON); return h; } }
知止而后有定;定而后能静;静而后能安;安而后能虑;虑而后能得。
java网络URL请求编程入门
对于使用URL类请求网络服务器并接受请求进行简单处理的示例,记录下学习过程。
-
GET请求
-
代码示例如下
package testHttpGet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class TestGet { public static void main(String[] args) { new ReadByGet().start(); } static class ReadByGet extends Thread{ @Override public void run() { try { //根据URL地址创建一个URL对象 URL url = new URL("https://easy-mock.com/mock/5c2f632779696b7e93ba23d6/example/testhttpget"); //获取URL连接,open方法返回一个URLConnection类的对象 URLConnection conn = url.openConnection(); //从连接获取输入流,请求的输入也就是对请求的输入,即是相应, InputStream in = conn.getInputStream(); InputStreamReader is = new InputStreamReader(in); //将字节流转换成字符流,方便操作 BufferedReader br = new BufferedReader(is); String line = null; while((line = br.readLine())!=null) { //打印相应的内容 System.out.println(line); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
结果:返回一个html页面 - 内部类如果在静态方法里面创建对象必须是静态内部类,或者将其声明在外部。
-
POST请求
- 代码示例如下:
package testHttpGet; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class TestHttpPost { public static void main(String[] args) { new ReadByPost().start(); } static class ReadByPost extends Thread{ @Override public void run() { try { URL url = new URL("https://easy-mock.com/mock/5c2f632779696b7e93ba23d6/example/testhttpget"); //返回一个HttpURLConnection对象,他继承自URLConnection, HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置请求头 conn.addRequestProperty("encoding", "utf-8"); //设置允许对请求输入和输出参数,也就是对请求加上参数 conn.setDoInput(true); conn.setDoOutput(true); //设置请求方式为POST conn.setRequestMethod("POST"); OutputStream out = conn.getOutputStream(); OutputStreamWriter owt = new OutputStreamWriter(out); BufferedWriter bw = new BufferedWriter(owt); //对请求设置参数 bw.write("name=Tom&age=18"); //获取请求的响应,输入流 InputStream in = conn.getInputStream(); InputStreamReader is = new InputStreamReader(in); BufferedReader br = new BufferedReader(is); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
注意点:设置请求参数之前必须先设置请求方式为POST,否则会抛出异常,输入流和输出流的先后顺序也不能颠倒,因为是先请求再得到响应,所以是输出流在前,为请求设置请求参数,
输入流在后,就是得到的响应的具体内容!
以上是关于Java 网络请求的主要内容,如果未能解决你的问题,请参考以下文章