java 获得url端口的工具类_java连接外部接口获取数据工具类

package com.yqzj.util;

import org.apache.log4j.LogManager;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.URL;

import java.net.URLConnection;

public class HttpRequestUtil {

/** 日志 */

private static Logger log = LogManager.getLogger(HttpRequestUtil.class);

/**

* 向指定URL发送GET方法的请求

* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。

* @param url

* 发送请求的URL

* @return URL 所代表远程资源的响应结果

*/

public static String sendGet(String url) {

StringBuilder result = new StringBuilder();

BufferedReader in = null;

try {

URL realUrl = new URL(url);

// 打开和URL之间的连接

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.setRequestProperty("Accept-Charset", "UTF-8");

connection.setRequestProperty("contentType", "UTF-8");

// 建立实际的连接

connection.connect();

// 遍历所有的响应头字段

// for (String key : map.keySet()) {

// System.out.println(key + "--->" + map.get(key));

// }

// 定义 BufferedReader输入流来读取URL的响应

in = new BufferedReader(new InputStreamReader(

connection.getInputStream(), "utf-8"));

String line;

while ((line = in.readLine()) != null) {

result.append(line);

}

} catch (Exception e) {

//System.out.println("发送GET请求出现异常!" + e);

result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");

e.printStackTrace();

log.error("远程服务未开启", e);

}

// 使用finally块来关闭输入流

finally {

try {

if (in != null) {

in.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return result.toString();

}

/**

* 向指定 URL 发送POST方法的请求

*

* @param url

* 发送请求的 URL

* @param param

* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。

* @return 所代表远程资源的响应结果

*/

public static String sendPost(String url, String param) {

PrintWriter out = null;

BufferedReader in = null;

StringBuilder result = new StringBuilder();

try {

URL realUrl = new URL(url);

// 打开和URL之间的连接

URLConnection conn = realUrl.openConnection();

// 设置通用的请求属性

conn.setRequestProperty("accept", "*/*");

conn.setRequestProperty("connection", "Keep-Alive");

conn.setRequestProperty("user-agent",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

conn.setRequestProperty("Accept-Charset", "UTF-8");

conn.setRequestProperty("contentType", "UTF-8");

// 发送POST请求必须设置如下两行

conn.setDoOutput(true);

conn.setDoInput(true);

// 获取URLConnection对象对应的输出流

out = new PrintWriter(conn.getOutputStream());

// 发送请求参数

out.print(param);

// flush输出流的缓冲

out.flush();

// 定义BufferedReader输入流来读取URL的响应

in = new BufferedReader(

new InputStreamReader(conn.getInputStream()));

String line;

while ((line = in.readLine()) != null) {

result.append(line);

}

} catch (Exception e) {

//System.out.println("发送 POST 请求出现异常!" + e);

result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");

e.printStackTrace();

log.error("远程服务未开启", e);

}

// 使用finally块来关闭输出流、输入流

finally {

try {

if (out != null) {

out.close();

}

if (in != null) {

in.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

return result.toString();

}

/**

* 向指定 URL 发送POST方法的请求

*

* @param url

* 发送请求的 URL

* @param param

* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。

* @return 所代表远程资源的响应结果

*/

public static String sendFile(String url, String param,

BufferedInputStream bInputStream) {

BufferedOutputStream out = null;

BufferedReader in = null;

StringBuilder result = new StringBuilder();

try {

URL realUrl = new URL(url);

// 打开和URL之间的连接

URLConnection conn = realUrl.openConnection();

// 设置通用的请求属性

conn.setRequestProperty("accept", "*/*");

conn.setRequestProperty("connection", "Keep-Alive");

conn.setRequestProperty("user-agent",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

conn.setRequestProperty("Accept-Charset", "UTF-8");

conn.setRequestProperty("contentType", "multipart/form-data");

// 发送POST请求必须设置如下两行

conn.setDoOutput(true);

conn.setDoInput(true);

// 发送参数

StringBuffer sb = new StringBuffer();

sb = sb.append(param);

byte[] paramData = sb.toString().getBytes();

//System.out.println(paramData.length);

out = new BufferedOutputStream(conn.getOutputStream());

out.write(paramData);

if (bInputStream != null) {

byte[] data = new byte[2048];

while (bInputStream.read(data) != -1) {

out.write(data);

}

}

out.flush();

// flush输出流的缓冲

// 定义BufferedReader输入流来读取URL的响应

in = new BufferedReader(

new InputStreamReader(conn.getInputStream()));

String line;

while ((line = in.readLine()) != null) {

result.append(line);

}

} catch (Exception e) {

//System.out.println("发送 POST 请求出现异常!" + e);

result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");

e.printStackTrace();

}

// 使用finally块来关闭输出流、输入流

finally {

try {

if (out != null) {

out.close();

}

if (in != null) {

in.close();

}

if (bInputStream != null) {

bInputStream.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

return result.toString();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Java中的Socket类来获取服务端的IP地址端口号。以下是一个简单的工具类示例: ```java import java.net.InetAddress; import java.net.Socket; public class ServiceInfoUtil { /** * 获取服务端IP地址端口号 * @param hostname 服务端主机名 * @param port 服务端端口号 * @return 包含服务端IP地址端口号的字符串 */ public static String getServiceInfo(String hostname, int port) { try { // 创建socket并连接到服务端 Socket socket = new Socket(hostname, port); // 获取服务端的IP地址端口号 InetAddress address = socket.getInetAddress(); int serverPort = socket.getPort(); // 关闭socket socket.close(); // 返回包含服务端IP地址端口号的字符串 return "Service running at: " + address.getHostAddress() + ":" + serverPort; } catch (Exception e) { // 如果连接失败则返回null return null; } } } ``` 使用示例: ```java String serviceInfo = ServiceInfoUtil.getServiceInfo("localhost", 8080); if (serviceInfo != null) { System.out.println(serviceInfo); } else { System.out.println("Failed to connect to service."); } ``` 在上面的示例中,我们通过调用`getServiceInfo`方法来获取`localhost:8080`服务的IP地址端口号。如果连接成功,则返回包含服务端IP地址端口号的字符串,否则返回null。 ### 回答2: 在Java中编写一个获取服务IP端口工具类,可以使用Java的Socket类进行实现。 首先,我们需要创建一个名为"ServerUtils"的工具类。在这个工具类中,我们可以定义一个静态方法,用于获取指定服务的IP和端口。下面是具体的实现步骤: 1. 导入必要的Java包: ```java import java.net.InetSocketAddress; import java.net.Socket; ``` 2. 定义静态方法"getServerIPAndPort",该方法接受两个参数:服务的主机名和端口号,并返回一个包含IP和端口字符串数组: ```java public class ServerUtils { public static String[] getServerIPAndPort(String hostname, int port) { String[] results = new String[2]; try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(hostname, port)); results[0] = socket.getLocalAddress().getHostAddress(); // 获取本地IP results[1] = String.valueOf(socket.getLocalPort()); // 获取本地端口 socket.close(); } catch (Exception e) { e.printStackTrace(); } return results; } } ``` 3. 调用这个方法来获取服务的IP和端口,示例代码如下: ```java public class Main { public static void main(String[] args) { String hostname = "localhost"; // 服务主机名 int port = 8080; // 服务端口 // 调用获取IP和端口的方法 String[] ipAndPort = ServerUtils.getServerIPAndPort(hostname, port); if (ipAndPort[0] != null && ipAndPort[1] != null) { System.out.println("服务IP地址:" + ipAndPort[0]); System.out.println("服务端口号:" + ipAndPort[1]); } else { System.out.println("无法获取服务的IP和端口。"); } } } ``` 以上就是使用Java编写一个获取服务IP和端口工具类的步骤。可以根据实际的服务主机名和端口号来调用这个工具类获取对应的IP和端口信息。 ### 回答3: 下面是一个用Java编写的获取服务IP端口工具类: ```java import java.net.InetAddress; import java.net.Socket; public class ServiceUtils { public static String getServiceIP(String hostname) { try { InetAddress address = InetAddress.getByName(hostname); return address.getHostAddress(); } catch (Exception e) { e.printStackTrace(); } return null; } public static int getServicePort(String hostname, int port) { try { Socket socket = new Socket(hostname, port); int servicePort = socket.getLocalPort(); socket.close(); return servicePort; } catch (Exception e) { e.printStackTrace(); } return -1; } public static void main(String[] args) { String hostname = "example.com"; // 服务主机名 int port = 80; // 服务端口号 String serviceIP = getServiceIP(hostname); int servicePort = getServicePort(hostname, port); System.out.println("服务IP:" + serviceIP); System.out.println("服务端口:" + servicePort); } } ``` 以上是一个基于Java工具类,可以通过提供服务的主机名和端口号来获取服务的IP地址端口。其中,`getServiceIP`方法通过主机名获取对应的IP地址,`getServicePort`方法通过主机名和端口获取服务的端口号。在`main`方法中,可以通过调用这两个方法来获取服务的IP和端口,并打印输出。请根据实际需求修改`hostname`和`port`的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值