转:https://www.cnblogs.com/brokencolor/p/8575440.html
Java的URL类(二)
实例:
Java 通过HttpURLConnection Post方式提交json,并从服务端返回json数据
package Demo.Test; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class App { public static void readParse(String urlPath,String str) throws Exception { System.out.println(str); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置传递方式 conn.setRequestMethod("POST"); //代理 conn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); //权限 conn.setRequestProperty("Authorization", " Bearer fc58be57c46b32f9a2c32e5393684ac0"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write((str).getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { System.out.println("连接成功"); // 请求返回的数据 InputStream in = conn.getInputStream(); String a = null; try { byte[] data1 = new byte[in.available()]; in.read(data1); // 转成字符串 a = new String(data1); System.out.println(a); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.out.println(conn.getResponseCode()+":no++"); } } public static void main(String[] args) throws Exception {//地址 String url = "http://..."; //查询参数 String str = "{"ids":[15410,15402]}"; readParse(url,str); } }
注:如果你的代码报错:java.io.IOException: Server returned HTTP response code: 403 for URL https://...... 访问被拒绝
你需要在代码中加入请求头信息
// 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 设置文件长度 conn.setRequestProperty("Content-Length", String.valueOf(data.length)); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); //代理 conn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //权限---需要根据自己情况进行修改 conn.setRequestProperty("Authorization", " Bearer fc58be57c46b32f9a2c32e5393684ac0");
GET方式访问weatherAPI接口实例
1 import java.io.InputStream; 2 import java.net.URL; 3 import java.net.URLConnection; 4 5 public class WeatherAPI { 6 7 public static void main(String[] args) throws Exception { 8 // TODO Auto-generated method stub 9 WeatherAPI.json("北京"); 10 //3秒后继续执行 11 Thread.sleep(3000); 12 WeatherAPI.xml("东京"); 13 } 14 public static void json(String strcity) throws Exception{ 15 //参数url化 16 String city = java.net.URLEncoder.encode(strcity, "utf-8"); 17 //拼地址 18 String apiUrl = String.format("https://www.sojson.com/open/api/weather/json.shtml?city=%s",city); 19 //开始请求 20 URL url= new URL(apiUrl); 21 URLConnection open = url.openConnection(); 22 InputStream input = open.getInputStream(); 23 //这里转换为String,带上包名,怕你们引错包 24 String result = org.apache.commons.io.IOUtils.toString(input,"utf-8"); 25 //输出 26 System.out.println(result); 27 } 28 29 public static void xml(String strcity) throws Exception{ 30 //参数url化 31 String city = java.net.URLEncoder.encode(strcity, "utf-8"); 32 //拼地址 33 String apiUrl = String.format("https://www.sojson.com/open/api/weather/xml.shtml?city=%s",city); 34 //开始请求 35 URL url= new URL(apiUrl); 36 URLConnection open = url.openConnection(); 37 InputStream input = open.getInputStream(); 38 //这里转换为String,带上包名,怕你们引错包 39 String result = org.apache.commons.io.IOUtils.toString(input,"utf-8"); 40 //输出 41 System.out.println(result); 42 } 43 }