JAVA使用HTTP代码示例
以下是使用Java发送HTTP请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("Example Domain");
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法
conn.setRequestMethod("GET");
// 获取响应码
int responseCode = conn.getResponseCode();
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应内容
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码使用了`HttpURLConnection`类来发送HTTP请求,并读取响应内容。你可以根据需要修改请求方法、请求头、请求体等参数。
import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.Authenticator;import java.net.HttpURLConnection;import java.net.InetSocketAddress;import java.net.PasswordAuthentication;import java.net.Proxy;import java.net.URL;class ProxyAuthenticator extends Authenticator {private String user, password;public ProxyAuthenticator(String user, String password) {this.user = user;this.password = password;}protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(user, password.toCharArray());}}/*** 注意:下面代码仅仅实现HTTP请求链接,每一次请求都是无状态保留的,仅仅是这次请求是更换IP的,如果下次请求的IP地址会改变* 如果是多线程访问的话,只要将下面的代码嵌入到你自己的业务逻辑里面,那么每次都会用新的IP进行访问,如果担心IP有重复,* 自己可以维护IP的使用情况,并做校验。*/public class ProxyDemo {public static void main(String args[]) throws Exception {// 要访问的目标页面String targetUrl = "http://ip.hahado.cn/ip";//String targetUrl = "http://ip.hahado.cn/switch-ip";//String targetUrl = "http://ip.hahado.cn/current-ip";// 代理服务器String proxyServer = "ip.hahado.cn";int proxyPort = 39010;// 代理隧道验证信息String proxyUser = "username";String proxyPass = "password";try {URL url = new URL(targetUrl);Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));// 创建代理服务器地址对象InetSocketAddress addr = new InetSocketAddress(proxyServer, proxyPort);// 创建HTTP类型代理对象Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);// 设置通过代理访问目标页面HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);// 设置IP切换头connection.setRequestProperty("Proxy-Switch-Ip","yes");// 解析返回数据byte[] response = readStream(connection.getInputStream());System.out.println(new String(response));} catch (Exception e) {System.out.println(e.getLocalizedMessage());}}/*** 将输入流转换成字符串** @param inStream* @return* @throws Exception*/public static byte[] readStream(InputStream inStream) throws Exception {ByteArrayOutputStream outSteam = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = -1;while ((len = inStream.read(buffer)) != -1) {outSteam.write(buffer, 0, len);}outSteam.close();inStream.close();return outSteam.toByteArray();}}