1、使用HttpClient
2、所需的依賴jar包: commons-codec-1.9.jar
commons-httpclient-3.1.jar
3、具體代碼
1 try { 2 HttpClient client = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true)); 3 HttpMethod method = null; 4 String uri = "{接口的uRL直接帶參數}}"; 5 method = new GetMethod(uri); 6 7 //瀏覽器的requestHeader 模擬瀏覽器 8 method.setRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"); 9 method.setRequestHeader("Accept","image/webp,image/*,*/*;q=0.8"); 10 method.setRequestHeader("Cookie","ORA_BIPS_LBINFO=157b18e65d9; ORA_BIPS_NQID=jifecsdccfgkctabqnhk687a48hdaqsthos17jofllohscns"); 11 try { 12 //執行getMethod 13 int statusCode = client.executeMethod(method); 14 if (statusCode != HttpStatus.SC_OK) { 15 System.err.println("Method failed: "+ method.getStatusLine()); 16 } 17 //讀取內容 18 String dataXml = method.getResponseBodyAsString(); 19 //處理內容 20 System.out.println(new String(dataXml)); 21 JSONObject json = Xml2JsonUtil.xml2JSON(dataXml); 22 response.setContentType("text/plain; charset=UTF-8"); 23 response.getWriter().write(json.toString()); 24 response.getWriter().flush(); 25 response.getWriter().close(); 26 } catch (HttpException e) 27 { 28 //發生致命的異常,可能是協議不對或者返回的內容有問題 29 System.out.println("Please check your provided http address!"); 30 e.printStackTrace(); 31 } catch (IOException e) { 32 //發生網絡異常 33 e.printStackTrace(); 34 } finally { 35 //釋放連接 36 method.releaseConnection(); 37 } 38 }catch(Exception e) 39 { 40 e.printStackTrace(); 41 }