我只用到了get, 暂时先记下get方式吧
1. get方式
public class TestHttpGet {
private static final String URL = "";
public String sendGet( ) {
String result = "";
BufferedReader in = null;
try {
// 打开和URL之间的连接
URLConnection connection = new URL( url ).openConnection( );
// 设置通用的请求属性
connection.setRequestProperty( "accept", "*/*" );
// 建立实际的连接
connection.connect( );
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader( new InputStreamReader( connection.getInputStream( ), "GBK" ) );
String line;
while ( ( line = in.readLine( ) ) != null ) {
result += line;
}
} catch ( Exception e ) {
System.out.println( "发送GET请求出现异常!" + e );
e.printStackTrace( );
}
// 使用finally块来关闭输入流
finally {
try {
if ( in != null ) {
in.close( );
}
} catch ( Exception e2 ) {
e2.printStackTrace( );
}
}
System.out.println( result );
return result;
}
public static void main( String[] aaa ) {
new TestHttpGet( ).sendGet( );
}
}
填写URL运行即可访问
new InputStreamReader( )没有指定编码的时候, 返回的中文都是乱码
网上找到这个方法, 在这里加上字符编码, 就好了, 目前我还没理解, 以后慢慢了解, 先解决问题;