精华内容
下载资源
问答
  • JAVA后台访问url

    千次阅读 2018-01-15 11:24:24
    public static String SendGET(String url,String param){  String result="";//访问返回结果  BufferedReader read=null;//读取访问结果    try {  //创建url  URL realurl=new ...
    public static String SendGET(String url,String param){
       String result="";//访问返回结果
       BufferedReader read=null;//读取访问结果
        
       try {
        //创建url
        URL realurl=new URL(url+"?"+param);
        //打开连接
        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();
              // 获取所有响应头字段
                 Map<String, List<String>> map = connection.getHeaderFields();
                 // 遍历所有的响应头字段,获取到cookies等
                 for (String key : map.keySet()) {
                     System.out.println(key + "--->" + map.get(key));
                 }
                 // 定义 BufferedReader输入流来读取URL的响应
                 read = new BufferedReader(new InputStreamReader(
                         connection.getInputStream(),"UTF-8"));
                 String line;//循环读取
                 while ((line = read.readLine()) != null) {
                     result += line;
                 }
       catch (IOException e) {
        e.printStackTrace();
       }finally{
        if(read!=null){//关闭流
         try {
          read.close();
         catch (IOException e) {
          e.printStackTrace();
         }
        }
       }
         
       return result; 
     }
    展开全文
  • java后台访问url

    2011-12-24 13:15:47
    中心编码问题是一个老问题了,一直没得到很好的解决,望大牛们指点迷津 :D [code="java"]public static String callUrlByGet(String callurl,String ... URL url = new URL(callurl); URLConnect...
    中心编码问题是一个老问题了,一直没得到很好的解决,望大牛们指点迷津 :D 
    public static String callUrlByGet(String callurl,String charset){

    String result = "";
    try {
    URL url = new URL(callurl);
    URLConnection connection = url.openConnection();
    connection.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),charset));
    String line;
    while((line = reader.readLine())!= null){
    result += line;
    result += "\n";
    }

    } catch (Exception e) {
    e.printStackTrace();
    return "";
    }
    return result;
    }
    展开全文
  • JAVA后台访问URL接口 package mon.utils; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Print
  • import java.net.URL; import java.nio.charset.Charset; import XmlHelper; public class QXOutStream { public String outPutStr(String urlStr, String input) throws Exception{ StringBuffer strBuf = new ...

    QXOutStream outPut= new QXOutStream();

    qxWorkSheetXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

    qxWorkSheetXML.append("");

    qxWorkSheetXML.append(""+call_man+"");

    qxWorkSheetXML.append(""+call_time+"");

    qxWorkSheetXML.append(""+workSheetNo+"");

    qxWorkSheetXML.append(""+call_no+"");

    qxWorkSheetXML.append(""+deadLine+"");

    qxWorkSheetXML.append("");

    returnStr=outPut.outPutStr(urlStr, qxWorkSheetXML.toString());

    import java.io.BufferedInputStream;

    import java.io.BufferedOutputStream;

    import java.io.BufferedReader;

    import java.io.InputStreamReader;

    import java.net.HttpURLConnection;

    import java.net.URL;

    import java.nio.charset.Charset;

    import XmlHelper;

    public class QXOutStream {

    public String outPutStr(String urlStr, String input) throws Exception{

    StringBuffer strBuf = new StringBuffer();

    String Resulst="";

    try{

    URL url = new URL(urlStr);

    HttpURLConnection con = (HttpURLConnection)url.openConnection();

    con.setDoInput(true);

    con.setDoOutput(true);

    con.setRequestMethod("POST");

    con.setAllowUserInteraction(false);

    con.setUseCaches(false);

    con.setRequestProperty("Accept-Charset", "GBK");

    BufferedOutputStream bufOutPut = new BufferedOutputStream(con.getOutputStream());

    byte[] bdat = input.getBytes("UTF-8");//解决中文乱码问题

    bufOutPut.write(bdat, 0, bdat.length);

    bufOutPut.flush();

    BufferedInputStream inp = new BufferedInputStream(con.getInputStream());

    InputStreamReader in = new InputStreamReader(inp,Charset.forName("GBK"));

    BufferedReader bufReador = new BufferedReader(in);

    String tempStr = "";

    while (tempStr != null) {

    strBuf.append(tempStr);

    tempStr = bufReador.readLine();

    }

    Resulst = XmlHelper.getPostNodeText(strBuf.toString(), "OPERATOR_RESULT");//.getPostFirstRowText(strBuf.toString(), "OPERATOR_RESULT");

    }

    catch (Exception e) {

    //System.err.println("Exception:"+e.toString());

    throw e;

    //return "N";

    }

    finally{

    return Resulst;

    }

    }

    }

    import java.io.InputStream;

    import java.net.URL;

    import java.net.URLConnection;

    import javax.xml.transform.TransformerException;

    import org.apache.log4j.Logger;

    import org.w3c.dom.Attr;

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.Node;

    import org.w3c.dom.NodeList;

    import com.sun.org.apache.xpath.internal.XPathAPI;

    /**

    * 处理XML的封装类

    */

    public abstract class XmlHelper {

    private XmlHelper() {

    }

    private static SimpleXmlParser parser = new SimpleXmlParser();

    private static Logger logger = Logger.getLogger(XmlHelper.class.getName());

    public static Document getDocument(String xmlStr) throws Exception {

    try {

    return parser.parseXml(xmlStr);

    } catch (Exception ex) {

    logger.error("得到Document出错-->", ex);

    throw ex;

    }

    }

    public static Document getDocumentFormStream(InputStream s)

    throws Exception {

    try {

    Document doc = parser.parse(s);

    return doc;

    } catch (Exception ex) {

    logger.error("从文件流中得到Document出现错误,错误为-->", ex);

    throw ex;

    }

    }

    public static Document getDocumentFormFile(String url) {

    try {

    URL u = new URL(url);

    URLConnection connection = u.openConnection();

    connection.setDoInput(true);

    connection.setUseCaches(false);

    Document doc = parser.parse(url);

    connection.getInputStream().close();

    return doc;

    } catch (Exception ex) {

    logger.info("从url中取得数据出错,错误为-->", ex);

    }

    return null;

    }

    public static NodeList selectNodeList(Node node, String xpath)

    throws TransformerException {

    try {

    return XPathAPI.selectNodeList(node, xpath);

    } catch (TransformerException ex) {

    logger.error("得到xml节点队列出错-->", ex);

    throw ex;

    }

    }

    public static Node selectSingleNode(Node node, String xpath)

    throws TransformerException {

    try {

    return XPathAPI.selectSingleNode(node, xpath);

    } catch (TransformerException ex) {

    logger.error("得到单一的xml节点出错-->", ex);

    throw ex;

    }

    }

    public static Node selectNode(Node node, String xpath) {

    for (int i = 0; i < node.getChildNodes().getLength(); i++) {

    Node childNode = node.getChildNodes().item(i);

    if (childNode.getNodeType() == Node.ELEMENT_NODE

    && childNode.getNodeName().equals(xpath))

    return childNode;

    }

    return null;

    }

    public static Attr getAttribute(Node node, String attName) {

    return (Attr) node.getAttributes().getNamedItem(attName);

    }

    public static String getNodeText(Node node) {

    for (int i = 0; i < node.getChildNodes().getLength(); i++) {

    if (node.getChildNodes().item(i).getNodeType() == Node.TEXT_NODE)

    return node.getChildNodes().item(i).getNodeValue();

    }

    return null;

    }

    public static String getPostNodeText(String postString, String nodeName) {

    try {

    Document doc = getDocument(postString);

    Element root = doc.getDocumentElement();

    NodeList list = root.getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {

    Node node = list.item(i);

    if (node.getNodeType() == Node.ELEMENT_NODE) {

    logger.debug("node:" + node.getNodeType() + ","

    + node.getNodeName());

    if (node.getNodeName().equals(nodeName))

    return getNodeText(node);

    }

    }

    } catch (Exception ex) {

    logger.error("从post信息中得到xml解析数据出错-->", ex);

    }

    return null;

    }

    public static String getPostFirstRowText(String postString, String nodeName) {

    try {

    return XmlHelperJdom.getFirstRowData(postString, nodeName);

    } catch (Exception ex) {

    logger.error("从post的第一行数据中得到xml解析数据出错-->", ex);

    }

    return null;

    }

    /*

    * 添加一个节点,并且设置其text

    */

    public static org.dom4j.Element addElementAndSetValue(

    org.dom4j.Element parent, String name, String value) {

    if (null == name)

    return null;

    org.dom4j.Element e = parent.addElement(name);

    if (null == value) {

    value = "";

    }

    e.setText(value);

    return e;

    }

    }

    展开全文
  • java后台访问url需要的包,没时间好好整理,包可能多几个
  • java后台访问url连接——HttpClients

    万次阅读 2015-07-13 11:25:12
    java后台访问url,并获取或者传递数据 1、无参数传递,以微信开发为例,后台访问url连接获得全部的人员列表 /** * 获取全部人员列表 * @return */ public JSONObject getAllEmployee(){ //获取微信号 ...

    java后台访问url,并传递数据——通过httpclient方式

    需要的包,包可能多几个额外的,如果无用或者冲突删除即可,httpclient是使用的是4.4.1的版本:http://download.csdn.net/detail/myfmyfmyfmyf/8894191

    1、无参数传递,以微信开发为例,后台访问url连接获得全部的人员列表

    	/**
    	 * 获取全部人员列表
    	 * @return
    	 */
        public  JSONObject getAllEmployee(){
        	//获取微信号
        	String token=getTokenFromWx();
        	 String dep_root=ROOT_DEP;//跟部门树
    		 try {
    			 CloseableHttpClient httpclient = HttpClients.createDefault();
    			 HttpPost httpPost= new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token="+token+"&department_id="+dep_root+"&fetch_child="+FETCH_CHILD+"&status="+STATE);
    			 // Create a custom response handler
    			 ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
    				//成功调用连接后,对返回数据进行的操作
                    public JSONObject handleResponse(
                            final HttpResponse response) throws ClientProtocolException, IOException {
                        int status = response.getStatusLine().getStatusCode();
                        if (status >= 200 && status < 300) {
                        	//获得调用成功后  返回的数据
                            HttpEntity entity = response.getEntity();
                            if(null!=entity){
                            	String result= EntityUtils.toString(entity);
                                //根据字符串生成JSON对象
                       		 	JSONObject resultObj = JSONObject.fromObject(result);
                       		 	return resultObj;
                            }else{
                            	return null;
                            }
                        } else {
                            throw new ClientProtocolException("Unexpected response status: " + status);
                        }
                    }
    
                };
              //返回的json对象
                JSONObject responseBody = httpclient.execute(httpPost, responseHandler);
                //System.out.println(responseBody);
                return responseBody; 
    		 }catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}       
        }


     

    2、有参数传递,以微信开发为例,后台访问url主动发送消息(json数据),httpClient通过设置StringEntity对象传递

    /**
      	 * 主动发送消息
      	 * @param mess
      	 * @return
      	 */
      	public  boolean sendReqMsg(ReqBaseMessage mess){
      		//消息json格式
      		String jsonContext=mess.toJsonStr();
      		//System.out.println(jsonContext);
      		//获得token
      		String token=getTokenFromWx();
    		 boolean flag=false;
    		 try {
    			 CloseableHttpClient httpclient = HttpClients.createDefault();
    			 HttpPost httpPost= new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token);
    			 //发送json格式的数据
    			 StringEntity myEntity = new StringEntity(jsonContext, 
    					   ContentType.create("text/plain", "UTF-8"));
    			 //设置需要传递的数据
    			 httpPost.setEntity(myEntity);
    			 // Create a custom response handler
                ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
                	//对访问结果进行处理
                    public JSONObject handleResponse(
                            final HttpResponse response) throws ClientProtocolException, IOException {
                        int status = response.getStatusLine().getStatusCode();
                        if (status >= 200 && status < 300) {
                            HttpEntity entity = response.getEntity();
                            if(null!=entity){
                            	String result= EntityUtils.toString(entity);
                                //根据字符串生成JSON对象
                       		 	JSONObject resultObj = JSONObject.fromObject(result);
                       		 	return resultObj;
                            }else{
                            	return null;
                            }
                        } else {
                            throw new ClientProtocolException("Unexpected response status: " + status);
                        }
                    }
    
                };
              //返回的json对象
                JSONObject responseBody = httpclient.execute(httpPost, responseHandler);
                System.out.println(responseBody);
                int result= (Integer) responseBody.get("errcode");
                if(0==result){
                	flag=true;
                }else{
                	flag=false;
                }
    			httpclient.close();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		 return flag;
    	}


    3、传递图片、文件等媒体信息,还是以微信开发为例

    /**
         * 文件上传到微信服务器
         * @param fileType 文件类型 媒体文件类型,分别有图片(image)、语音(voice)、视频(video),普通文件(file)
         * @param filePath 文件路径
         * @return JSONObject
         * @throws Exception
         */
        public  JSONObject send(String fileType, String filePath) throws Exception {  
            String result = null;  
            File file = new File(filePath);  
            if (!file.exists() || !file.isFile()) {  
                throw new IOException("文件不存在");  
            }  
            String token=getTokenFromWx();
            /** 
            * 第一部分 
            */  
            URL urlObj = new URL("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+ token 
            		+ "&type="+fileType+""); 
            					  
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();  
            con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式  
            con.setDoInput(true);  
            con.setDoOutput(true);  
            con.setUseCaches(false); // post方式不能使用缓存  
            // 设置请求头信息  
            con.setRequestProperty("Connection", "Keep-Alive");  
            con.setRequestProperty("Charset", "UTF-8");  
            // 设置边界  
            String BOUNDARY = "----------" + System.currentTimeMillis();  
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
            // 请求正文信息  
            // 第一部分:  
            StringBuilder sb = new StringBuilder();  
            sb.append("--"); // 必须多两道线  
            sb.append(BOUNDARY);  
            sb.append("\r\n");  
            sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName() + "\"\r\n");  
            sb.append("Content-Type:application/octet-stream\r\n\r\n");  
            byte[] head = sb.toString().getBytes("utf-8");  
            // 获得输出流  
            OutputStream out = new DataOutputStream(con.getOutputStream());  
            // 输出表头  
            out.write(head);  
            // 文件正文部分  
            // 把文件已流文件的方式 推入到url中  
            DataInputStream in = new DataInputStream(new FileInputStream(file));  
            int bytes = 0;  
            byte[] bufferOut = new byte[1024];  
            while ((bytes = in.read(bufferOut)) != -1) {  
            out.write(bufferOut, 0, bytes);  
            }  
            in.close();  
            // 结尾部分  
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
            out.write(foot);  
            out.flush();  
            out.close();  
            StringBuffer buffer = new StringBuffer();  
            BufferedReader reader = null;  
            try {  
            // 定义BufferedReader输入流来读取URL的响应  
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
            //System.out.println(line);  
            buffer.append(line);  
            }  
            if(result==null){  
            result = buffer.toString();  
            }  
            } catch (IOException e) {  
            System.out.println("发送POST请求出现异常!" + e);  
            e.printStackTrace();  
            throw new IOException("数据读取异常");  
            } finally {  
            if(reader!=null){  
            reader.close();  
            }  
            }  
            JSONObject jsonObj =JSONObject.fromObject(result);  
            return jsonObj;  
        }


     

    展开全文
  • 这是文章【JAVA】百度地图经纬度纠偏(http://blog.csdn.net/hj7jay/article/details/70308263) 所用到的jar包
  • 使用java访问url,可传普通参数和Header参数
  • 1、直接上代码 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException;...import java.net.URL; import java.net.URLConnection
  • Java后台访问URL并解析结果集

    千次阅读 2018-05-07 14:45:02
    try块里面的都可以直接复制,把url改成自己的就可以了,参数什么的就跟你在网页上访问接口一样 String code = "123456"; //这里随便定义一个code值,因为微信提供的code需要特定方式获取,而且只能用一...
  • java后台访问网址url

    千次阅读 2019-04-10 18:28:44
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException { JSONObject jsonObject =null; DefaultHttpClient client = new DefaultHttpClient()...
  • java后台访问接口

    2016-08-04 11:18:00
    java后台访问接口 // 发送url地址获取信息 public static String sendPost(String jsonStr, String path) { String msg = "";// 保存调用http服务后的响应信息 try { byte[]...
  • java后台获取url中的域名

    千次阅读 2019-10-21 14:11:42
    /** * @description 获取域名,如果是ip访问,如127.0.0.1 返回.0.0.1 *如果是域名www.xxxx.com 返回.xxxx.com * @param * @return String */ public static fi...
  • Url url = new Url("http://xxx.com.xxx"); UrlConnection uc = url.openConnection(); InputStreamReader in = new InputStreamReader(uc.getInputStream(),"UTF-8"); BufferReader br = ...
  • 1. java后台访问url,通过默认浏览器打开  private static void browse(String url) throws Exception {  //获取操作系统的名字   String osName = System.getProperty("os.name", ""); ...
  • java web后台获取项目访问url

    千次阅读 2018-03-03 22:17:18
     public String getUrl(String protocol, String scheme){  String ip = "";  String port = "";  MBeanServer mBeanServer = null;  if (MBeanServerFactory.findMBeanServer(null).size() > 0)  { ...
  • 基于HttpClient的HttpUtils(后台访问URL)

    千次阅读 2010-06-29 20:11:00
    基于HttpClient的HttpUtils(后台访问URL)2009-10-12 17:18 import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util....
  • 项目中遇到一个这样的需求:在本系统A中组装参数,然后再根据系统B提供的部分uri,组装一个完整的url类似"http://127.0.0.1:8090/test/index.jsp?userId=123&prjId=51011;通过http协议来访问系统B。当点击系统A...
  • 2:GET请求:(和POST类似,唯一的区别就是get请求不用输出流写参数,但是需要将参数加入到url后) HTTP 接口说明 HTTP是hypertext transfer protocol(超文本传输协议)的简写,它是TCP/IP协...
  • 2:get请求 /** * 发送get请求 * @param url 请求路径 * @param params 请求参数,格式为key-value * @param header 请求头 * @return */ public String getData(String url, Map params, Map header) { String ...
  • 展开全部ajax调用java后台的方法,其实是通过url链接来访问,示例如下:packagecom.xxxx.xxxx.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql....
  • 方法类   @ResponseBody public AjaxJson getAjaxJson(HttpServletRequest request, HttpServletResponse ... String url = "http://外网接口";//调用sendPost方法时传入的外网接口地址 Ma...
  • 这两天在搞html访问后台接口,发现跨域是个问题,解决这个问题需要ajax请求做配置、Java接口增加适配。 html中ajax请求: $.ajax({ type: "POST", url: "http://192.168.2.120:8093/api/g...
  • 使用jar:commons-httpclient-3.1.jar方法:publicvoidfindTeacherJson(){Stringresp=null;HttpClientclient=newHttpClient();GetMethodhttpGet=newGetMethod("URL地址字符串");try{intstatusCode=client.exec...
  • 项目中遇到一个这样的需求:在本系统A中组装参数,然后再根据系统B提供的部分uri,组装一个完整的url类似 "http://127.0.0.1:8090/test/index.jsp?userId=123&amp;prjId=51011 ;通过http协议来访问系统B...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 423
精华内容 169
关键字:

java后台访问url

java 订阅