org.apache.http.impl.client.TargetAuthenticationStrategy#oauth.signpost.commonshttp.CommonsHttpOAuthConsumer源码实例Demo

下面列出了org.apache.http.impl.client.TargetAuthenticationStrategy#oauth.signpost.commonshttp.CommonsHttpOAuthConsumer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lams   文件: LtiOauthSigner.java
@Override
public HttpRequest sign(HttpRequest request, String key, String secret) throws LtiSigningException {
    CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
    try {
        String body = getRequestBody(request);
        String bodyHash = new String(Base64.encodeBase64(md.digest(body.getBytes())));

        HttpParameters params = new HttpParameters();
        params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
        signer.setAdditionalParameters(params);

        signer.sign(request);
    } catch (OAuthMessageSignerException|OAuthExpectationFailedException|OAuthCommunicationException|IOException e) {
        throw new LtiSigningException("Exception encountered while singing Lti request...", e);
    }
    return request;
}
 
源代码2 项目: lams   文件: IMSPOXRequest.java
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}
	//*LAMS* the following line was added by LAMS and also messageIdentifier was added to the line after it
	String messageIdentifier = UUID.randomUUID().toString();
	String xml = String.format(replaceResultMessage, messageIdentifier, StringEscapeUtils.escapeXml(sourcedid),
			StringEscapeUtils.escapeXml(score), dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
源代码3 项目: java-upwork   文件: OAuthClientTest.java
private OAuthClient getMockedClient() throws Exception {
	when(properties.getProperty("consumerKey")).thenReturn("key");
	when(properties.getProperty("consumerSecret")).thenReturn("secret");
	
	final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
       PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString())
                           .thenReturn(fileInputStreamMock);
	
	PowerMockito.whenNew(CommonsHttpOAuthConsumer.class).withArguments(Matchers.anyString(), Matchers.anyString())
                           .thenReturn(CommonsHttpOAuthConsumerMock);
       
       PowerMockito.whenNew(CommonsHttpOAuthProvider.class).withArguments(Matchers.anyString(), Matchers.anyString(), Matchers.anyString())
       					.thenReturn(CommonsHttpOAuthProviderMock);
       
       Config config = new Config(properties);
	
	OAuthClient client = new OAuthClient(config);
	
	return client;
}
 
源代码4 项目: basiclti-util-java   文件: LtiOauthSigner.java
@Override
public HttpRequest sign(HttpRequest request, String key, String secret) throws LtiSigningException {
    CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
    try {
        String body = getRequestBody(request);
        String bodyHash = new String(Base64.encodeBase64(md.digest(body.getBytes())));

        HttpParameters params = new HttpParameters();
        params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
        signer.setAdditionalParameters(params);

        signer.sign(request);
    } catch (OAuthMessageSignerException|OAuthExpectationFailedException|OAuthCommunicationException|IOException e) {
        throw new LtiSigningException("Exception encountered while singing Lti request...", e);
    }
    return request;
}
 
源代码5 项目: java-upwork   文件: OAuthClient.java
/**
 * Constructor
 * 
 * @param	properties Config properties
 * */
public OAuthClient(Config properties) {
	if (properties == null) {
		properties = new Config(null);  
	}
	
	consumerKey = properties.getProperty("consumerKey");
	consumerSecret = properties.getProperty("consumerSecret");

	mOAuthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}
 
源代码6 项目: basiclti-util-java   文件: IMSPOXRequest.java
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid,
	String score, String resultData, Boolean isUrl, String messageId) throws IOException, OAuthException, GeneralSecurityException
{
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}

	String messageIdentifier = StringUtils.isBlank(messageId) ? String.valueOf(new Date().getTime()) : messageId;
	String xml = String.format(ReplaceResultMessageTemplate,
		StringEscapeUtils.escapeXml(messageIdentifier),
		StringEscapeUtils.escapeXml(sourcedid),
		StringEscapeUtils.escapeXml(score),
		dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
源代码7 项目: shimmer   文件: OAuth1Utils.java
/**
 * Signs an HTTP post request for cases where OAuth 1.0 posts are
 * required instead of GET.
 *
 * @param unsignedUrl     - The unsigned URL
 * @param clientId        - The external provider assigned client id
 * @param clientSecret    - The external provider assigned client secret
 * @param token           - The access token
 * @param tokenSecret     - The 'secret' parameter to be used (Note: token secret != client secret)
 * @param oAuthParameters - Any additional parameters
 * @return The request to be signed and sent to external data provider.
 */
public static HttpRequestBase getSignedRequest(HttpMethod method,
                                               String unsignedUrl,
                                               String clientId,
                                               String clientSecret,
                                               String token,
                                               String tokenSecret,
                                               Map<String, String> oAuthParameters) throws ShimException {

    URL requestUrl = buildSignedUrl(unsignedUrl, clientId, clientSecret, token, tokenSecret, oAuthParameters);
    String[] signedParams = requestUrl.toString().split("\\?")[1].split("&");

    HttpRequestBase postRequest = method == HttpMethod.GET ?
        new HttpGet(unsignedUrl) : new HttpPost(unsignedUrl);
    String oauthHeader = "";
    for (String signedParam : signedParams) {
        String[] parts = signedParam.split("=");
        oauthHeader += parts[0] + "=\"" + parts[1] + "\",";
    }
    oauthHeader = "OAuth " + oauthHeader.substring(0, oauthHeader.length() - 1);
    postRequest.setHeader("Authorization", oauthHeader);
    CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(clientId, clientSecret);
    consumer.setSendEmptyTokens(false);
    if (token != null) {
        consumer.setTokenWithSecret(token, tokenSecret);
    }
    try {
        consumer.sign(postRequest);
        return postRequest;
    } catch (
        OAuthMessageSignerException
            | OAuthExpectationFailedException
            | OAuthCommunicationException e) {
        e.printStackTrace();
        throw new ShimException("Could not sign POST request, cannot continue");
    }
}
 
public OAuthConsumer getConsumer(User user) {
	OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	if (user != null) {
		String token = user.getToken();
		String secret = user.getSecret();
		if (token != null && secret != null) {
			consumer.setTokenWithSecret(token, secret);
		}
	}
	return consumer;
}
 
public void login(final String token, final String secret, final UserLoginHandler handler) {
	OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	consumer.setTokenWithSecret(token, secret);
	fetchUser(consumer, new EntityCallback<User>() {
		@Override
		public void call(User returnedUser) {
			
			if (returnedUser != null) {
				returnedUser.setToken(token);
				returnedUser.setSecret(secret);
				try {
					Dao<User, String> userDao = dataService.getHelper().getUserDao();
					if (userDao.getConnectionSource().isOpen()) {
						userDao.createOrUpdate(returnedUser);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			handler.onUserLogin(returnedUser);
			currentUser = returnedUser;
			setCurrentUser(returnedUser);
			doUserUpdate(returnedUser);
		}
	});
}
 
源代码10 项目: albert   文件: TestTwitterSocket.java
public static void main(String[] args) throws Exception {
	  OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
				Constants.ConsumerKey,
				Constants.ConsumerSecret);
	  consumer.setTokenWithSecret(Constants.AccessToken, Constants.AccessSecret);
	  
	  
    HttpParams params = new BasicHttpParams();
    // HTTP 协议的版本,1.1/1.0/0.9
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 字符集
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // 伪装的浏览器类型
    // IE7 是 
    // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
    //
    // Firefox3.03
    // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
    //
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("127.0.0.1", 1080);
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
      String[] targets = { "https://www.twitter.com"};
      for (int i = 0; i < targets.length; i++) {
        if (!conn.isOpen()) {
          Socket socket = new Socket(host.getHostName(), host.getPort());
          conn.bind(socket, params);
        }
        
	  
        BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
//        consumer.sign(request);
        
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);
        // 返回码
        System.out.println("<< Response: " + response.getStatusLine());
        // 返回的文件头信息
//        Header[] hs = response.getAllHeaders();
//        for (Header h : hs) {
//          System.out.println(h.getName() + ":" + h.getValue());
//        }
        // 输出主体信息
//        System.out.println(EntityUtils.toString(response.getEntity()));
        
        HttpEntity entry = response.getEntity();
        StringBuffer sb = new StringBuffer();
  	  if(entry != null)
  	  {
  	    InputStreamReader is = new InputStreamReader(entry.getContent());
  	    BufferedReader br = new BufferedReader(is);
  	    String str = null;
  	    while((str = br.readLine()) != null)
  	    {
  	     sb.append(str.trim());
  	    }
  	    br.close();
  	  }
  	  System.out.println(sb.toString());
  	  
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
          conn.close();
        } else {
          System.out.println("Connection kept alive...");
        }
      }
    } finally {
      conn.close();
    }
  }
 
源代码11 项目: oxAuth   文件: ToopherAPI.java
/**
 * Create an API object with the supplied credentials
 * 
 * @param consumerKey
 *            The consumer key for a requester (obtained from the developer portal)
 * @param consumerSecret
 *            The consumer secret for a requester (obtained from the developer portal)
 */
public ToopherAPI(String consumerKey, String consumerSecret) {
    httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpClient.getParams(),
                                    String.format("ToopherJava/%s", VERSION));

    consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}