1. 程式人生 > >java 呼叫介面程式碼例項

java 呼叫介面程式碼例項

package com.zhuoshi.jcbigdata.spark.jinjingzheng;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

/**
 * @author lx
 * @describe 呼叫進京證違法藉口
 *
 */
public class illegalInterfaceService {
    public void illegalInfo(String rowkey) throws Exception{
    	
	String url="http://xxxxxxxxx/taoPaiChe/taoPaiCheFenxiPage?rowkey="+rowkey;
	 URL restURL = new URL(url);
     /*
      * 此處的urlConnection物件實際上是根據URL的請求協議(此處是http)生成的URLConnection類 的子類HttpURLConnection
      */
     HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
     //請求方式
     conn.setRequestMethod("POST");
     //設定是否從httpUrlConnection讀入,預設情況下是true; httpUrlConnection.setDoInput(true);
     conn.setDoOutput(true);
     //allowUserInteraction 如果為 true,則在允許使用者互動(例如彈出一個驗證對話方塊)的上下文中對此 URL 進行檢查。
     conn.setAllowUserInteraction(false);
     PrintStream ps = new PrintStream(conn.getOutputStream());
     ps.close();
     BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     String line,resultStr="";
     while(null != (line=bReader.readLine()))
     {
     resultStr +=line;
     }
   
     System.out.println("違法資料---"+resultStr);
     bReader.close();
     //解析巢狀JSON
     JSONObject jsonobject = JSONObject.fromObject(new String(resultStr.toString()));
     jsonobject.get("illegalinfo");
   } 
}


參考:[https://www.cnblogs.com/angusbao/p/7677621.html](https://www.cnblogs.com/angusbao/p/7677621.html)