返回信息流想利用nforum的api搞点东西试试,但是验证过不了,nforum采用basic auth认证。
“当前nForum采用Baisc Auth的认证方式,在调用API时请将用户名密码作为Basic Auth的用户名密码。”
我根据apache网站给的example代码写的如下验证,但是总是返回“401 Unauthorized”
url本身是没有问题的,但是就是验证没法通过,是不是验证的方法不对?
哪里出问题了?
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
static final String BASIC_URL = "";
public static void main(String[] args) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
AuthScope as = new AuthScope(new HttpHost(BASIC_URL));
System.out.println(as.toString());
client.getCredentialsProvider().setCredentials(as, new UsernamePasswordCredentials("guest",""));
HttpGet get = new HttpGet(BASIC_URL+"/user/login.xml");
System.out.println("executing request" + get.getRequestLine());
HttpResponse res = client.execute(get);
HttpEntity entity = res.getEntity();
System.out.println("----------------------------------------");
System.out.println(res.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
client.getConnectionManager().shutdown();
}
这是一条镜像帖。来源:北邮人论坛 / java / #23972同步于 2012/11/28
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
[问题]怎么用defaulthttpclient实现basic auth验证?
cb
2012/11/28镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
【 在 cb 的大作中提到: 】
: 想利用nforum的api搞点东西试试,但是验证过不了,nforum采用basic auth认证。
: “当前nForum采用Baisc Auth的认证方式,在调用API时请将用户名密码作为Basic Auth的用户名密码。”
: 我根据apache网站给的example代码写的如下验证,但是总是返回“401 Unauthorized”
: ...................
不知道确切原因,但我觉得是请求的时候没有提供认证用的HTTP头。完全不加认证的时候确实是401。应该是因为某种原因,HttpClient并没有发送这个头。
检查一下BASIC_URL吧。
顺便秀一下Scala代码:
import dispatch._
object ByrBoardList extends App {
val appkey = "xxxxxxxxxxxxxxxxxx"
def byrSectionInfo(section: Int) =
url("http://api.byr.cn/section/%d.json".format(section)) <<? Map(
"appkey" -> appkey) as_! ("guest", "")
val respBody = Http(byrSectionInfo(6) OK as.String)()
println(respBody)
}
BASIC认证这里就只是as_!这个方法。
最近打算利用API做个libbyr4s,不过暂时是私用。
4s 是神马的缩写。。
【 在 wks 的大作中提到: 】
:
: 不知道确切原因,但我觉得是请求的时候没有提供认证用的HTTP头。完全不加认证的时候确实是401。应该是因为某种原因,HttpClient并没有发送这个头。
: 检查一下BASIC_URL吧。
: ...................
能解释一下这个appkey是加到代码的什么位置吗?
【 在 wks 的大作中提到: 】
:
: 不知道确切原因,但我觉得是请求的时候没有提供认证用的HTTP头。完全不加认证的时候确实是401。应该是因为某种原因,HttpClient并没有发送这个头。
: 检查一下BASIC_URL吧。
: ...................