How does java initiate an http request and call the post and get interfaces?
1. Java calls the post interface
1. Use URLConnection or HttpURLConnection
java comes with it, no need to download other jar packages
Called in URLConnection mode, if the interface response code is modified by the server, the return message cannot be received. The return message can only be received when the response code is correct
public static String sendPost(String url, String param) { OutputStreamWriter out = null; BufferedReader in = null; StringBuilder result = new StringBuilder(""); try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("Content-Type","application/json;charset=UTF-8"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 发送请求参数 out.write(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!"+e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ if(out!=null){ try { out.close(); }catch(Exception ex){} } if(in!=null){ try { in.close(); }catch(Exception ex){} } } return result.toString(); }
HttpURLConnection method called
//ms超时毫秒,url地址,json入参 public static String httpJson(int ms,String url,String json) throws Exception{ String err = "00", line = null; StringBuilder sb = new StringBuilder(); HttpURLConnection conn = null; BufferedWriter out = null; BufferedReader in = null; try{ conn = (HttpURLConnection) (new URL(url.replaceAll("/","/"))).openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setConnectTimeout(ms); conn.setReadTimeout(ms); conn.setRequestProperty("Content-Type","application/json;charset=utf-8"); conn.connect(); out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8")); out.write(new String(json.getBytes(), "utf-8")); out.flush();//发送参数 int code = conn.getResponseCode(); if (conn.getResponseCode()==200){ in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); while ((line=in.readLine())!=null) sb.append(line); }//接收返回值 }catch(Exception ex){ err=ex.getMessage(); } try{ if (out!=null) out.close(); }catch(Exception ex){}; try{ if (in!=null) in.close(); }catch(Exception ex){}; try{ if (conn!=null) conn.disconnect();}catch(Exception ex){} if (!err.equals("00")) throw new Exception(err); return sb.toString(); }
2. Use the jar package used by CloseableHttpClient
<dependency> <groupId>com.alibaba.csb.sdk</groupId> <artifactId>http-client</artifactId> <version>1.1.5.1</version> </dependency>
public static String httpPostJson(String url,String json) throws Exception{ String data=""; CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-Type", "application/json;charset=UTF-8"); StringEntity se = new StringEntity(json,Charset.forName("UTF-8")); se.setContentType("text/json"); se.setContentEncoding("UTF-8"); httppost.setEntity(se); response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); System.out.println("接口响应码:"+code); data = EntityUtils.toString(response.getEntity(), "utf-8"); EntityUtils.consume(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { if(response!=null){ try{response.close();}catch (IOException e){} } if(httpClient!=null){ try{httpClient.close();}catch(IOException e){} } } return data; }
3. Use the jar package used by HttpCaller
is the same as the jar package in the second one.
public static String sendPost(){ String result = ""; HttpParameters.Builder builder = HttpParameters.newBuilder(); builder.requestURL("URL") // 设置请求的URL .api("api") // 设置服务名 .version("version") // 设置版本号 .method("post") // 设置调用方式, get/post .accessKey("ak").secretKey("sk"); // 设置accessKey 和 设置secretKey // 设置请求参数(json格式) Map<String,String> param = new HashMap<String,String>(); param.put("key1","value1"); param.put("key2","value2"); //加密,没有加密则不需要encryptParam,直接用param Map<String,String> encryptParam = new HashMap<String,String>(); encryptParam.put("key3", getData(JSON.toJSONString(param))); ContentBody cb = new ContentBody(JSON.toJSONString(encryptParam)); builder.contentBody(cb); try { result = HttpCaller.invoke(builder.build()); } catch (Exception e) { e.printStackTrace(); } return result; } //自己的加密方式 public static String getData(String data1){ return "加密后的密文"; }
2. Java calls the get interface
Use the URLConnection that comes with java
//将map型转为请求参数型 public static String getUrlData(Map<Object, Object> data) throws Exception{ StringBuffer sb = new StringBuffer(); try { Set<Map.Entry<Object, Object>> entries = data.entrySet(); Iterator<Map.Entry<Object, Object>> iterators = entries.iterator(); while(iterators.hasNext()){ Map.Entry<Object, Object> next = iterators.next(); sb.append(next.getKey().toString().trim()).append("=").append(URLEncoder.encode(next.getValue() + "", "UTF-8").trim()).append("&"); } sb.deleteCharAt(sb.length() - 1); } catch (Exception e) { sb.append(e.toString()); } return sb.toString(); } //strUrl截止到?,例:http://127.0.0.1:8080/api/method? public static String httpGet(String strUrl){ Map<Object, Object> params = new HashMap<Object, Object>(); params.put("key1", "value1"); params.put("key2", "value2"); String url=strUrl + getUrlData(params); StringBuilder result = new StringBuilder(); BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } finally { if (in != null){ try { in.close(); }catch(Exception e2){} } } return result.toString(); }
The above is the detailed content of How does java initiate an http request and call the post and get interfaces?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.
