packagecom.http;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.Authenticator;importjava.net.PasswordAuthentication;...
package com.http;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.Authenticator;import java.net.PasswordAuthentication;import java.net.URL;public class Test{ static final String kuser = "";//用户名,测试已填写 static final String kpass = "";//密码,测试已填写 static class MyAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(kuser, kpass.toCharArray())); } } public static void main(String[] args) throws Exception { Authenticator.setDefault(new MyAuthenticator()); URL url = new URL(" http://api.t.sohu.com/users/show.xml"); InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); String str; while((str=reader.readLine())!=null) { System.out.println(str); } }}出现的错误:Exception in thread "main" java.io.IOException: Server returned HTTP response code: 401 for URL: http://api.t.sohu.com/users/show.xml at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at com.http.Test.main(Test.java:27)
展开