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(); }
2. Java ruft die Get-Schnittstelle auf
Verwenden Sie die URLConnection, die mit Java geliefert wird
//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(); }
Das obige ist der detaillierte Inhalt vonWie initiiert Java eine http-Anfrage, ruft den Beitrag auf und erhält Schnittstellen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!