简体   繁体   中英

What's the equivalent HttpClient Java code for this Dispatch Scala?

import dispatch._
val h = new Http
val req = url(url).as_!(username, password)
val handler = req << (payload, "application/xml") >:> identity
handler.apply { 
    case (200, _, Some(entity), _) => (200, Some(entity))
    case (status, _,_,_) => (status, None)
}
val response = h(handler)

I've tried this:

public static void postService(Profile user, String subject, String body){
    Credentials credentials = new UsernamePasswordCredentials(userName, authToken);
    AuthScope authScope = new AuthScope(baseUrl, 80, AuthScope.ANY_REALM);
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(baseUrl);

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(authScope, credentials);

    String payload = makePayload(user, subject, body);
    RequestEntity entity = null;
    try{
        entity = new StringRequestEntity(payload, CONTENT_TYPE, null);
    } catch(UnsupportedEncodingException e){
        e.printStackTrace();
    }
    post.setRequestEntity(entity);

    try{
        client.executeMethod(post);
    } catch(IOException e){
        e.printStackTrace();
    } catch(HTTPException e){
        e.printStackTrace();
    }
}

UPDATED - SOLVED: This was a misunderstanding of AuthScope. I figured it out, basically I was passing in the entire url w/protocol ie "https://mysite.com" rather than just "mysite.com" I resolved this issue.

This was a misunderstanding of AuthScope. I figured it out, basically I was passing in the entire url w/protocol ie "https://mysite.com" rather than just "mysite.com" I resolved this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM