无法发送发帖请求

时间:2019-05-15 21:39:06

标签: java rest http-post

我可以发送getRequest,但我不愿意发送发帖请求。它说:

  

“线程“ main”中的异常org.springframework.web.client.HttpClientErrorException $未经授权:401未经授权”

public static void main(String[] args) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, MalformedURLException {

    URL url = new URL(URI);
    Map<String, String> headerParams = new HashMap<String, String>();
    headerParams.put("oauth_consumer_key", consumerKey);
    //oauthParams.put("application_id", appID);
    headerParams.put("oauth_signature_method", signatureMethod);
    headerParams.put("oauth_timestamp", getTimestamp());
    headerParams.put("oauth_nonce", getNonce());
    headerParams.put("oauth_signature", generateSignature("POST", url, headerParams, requestBody, consumerSecret));

    Map<String, String> bodyParams = new HashMap<String, String>();

    bodyParams.put("projectId","157695242");
    bodyParams.put("folderId","157847884");
    bodyParams.put("resourceName","PDPXTestDoc_Test3_Java");
    bodyParams.put("resourceMimeType","application/x-thunderhead-ddv");

    //ResponseEntity<String> response = sendOAuth1Request(URI, consumerKey, consumerSecret, headerParams);
    ResponseEntity<String> response = sendOAuth1PostRequest(URI, consumerKey, consumerSecret, headerParams,bodyParams);

    System.out.println("Response in main");
    String str = new String(response.toString());
    System.out.println(response.toString().length());
    System.out.println(str);
}

 private static String normalizeParams(
        String httpMethod,
        URL url,
        Map<String, String> oauthParams,
        byte[] requestBody
    ) throws UnsupportedEncodingException
{

    // Sort the parameters in lexicographical order, 1st by Key then by Value
    Map<String, String> kvpParams = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    kvpParams.putAll(oauthParams); 

    // Place any query string parameters into a key value pair using equals ("=") to mark
    // the key/value relationship and join each parameter with an ampersand ("&")
    if (url.getQuery() != null)
    {
        for(String keyValue : url.getQuery().split("&"))
        {
        String[] p = keyValue.split("=");
        kvpParams.put(p[0],p[1]);
        }

    }

    /*
    // Include the body parameter if dealing with a POST or PUT request if
    if("POST".equals(httpMethod) || "PUT".equals(httpMethod)) 
    {
        String body = Base64.encodeBase64String(requestBody).replaceAll("\r\n", ""); // url encode
        // the body 2 times now before combining other params body =
        URLEncoder.encode(body, "UTF-8"); 
        body = URLEncoder.encode(body, "UTF-8");
        System.out.println("---->"+body.toString()); 
        kvpParams.put("body", body); 

    }
    */

    // separate the key and values with a "="
    // separate the kvp with a "&"
    StringBuilder combinedParams = new StringBuilder();
    String delimiter="";
    for(String key : kvpParams.keySet()) {
        combinedParams.append(delimiter);
        combinedParams.append(key);
        combinedParams.append("=");
        combinedParams.append(kvpParams.get(key));
        delimiter="&";
    }

    // url encode the entire string again before returning
    return URLEncoder.encode(combinedParams.toString(), "UTF-8");
}
public static String generateSignature(
        String httpMethod,
        URL url,
        Map<String, String> oauthParams,
        byte[] requestBody,
        String secret
    ) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException
{
    // Ensure the HTTP Method is upper-cased
    httpMethod = httpMethod.toUpperCase();

    // Construct the URL-encoded OAuth parameter portion of the signature base string
    String encodedParams = normalizeParams(httpMethod, url, oauthParams, requestBody);

    // URL-encode the relative URL
    String encodedUri = URLEncoder.encode(url.getPath(), "UTF-8");

    // Build the signature base string to be signed with the Consumer Secret
    String baseString = String.format("%s&%s&%s", httpMethod, encodedUri, encodedParams);

    System.out.println("Sectet : "+secret);
    System.out.println("Base String: "+baseString);

    return hmacSha1(baseString, secret);
}

public static ResponseEntity sendOAuth1PostRequest(String url, String consumerKey, String sharedSecret, Map<String, String> headers,Map<String, String> params) {
    assert url != null;
    assert consumerKey != null;
    assert sharedSecret != null;
    Map<String, String> additionalparam = new HashMap<String, String>();
    additionalparam.put("Accept", "application/x-www-form-urlencoded");
    additionalparam.put("content-type", "application/x-www-form-urlencoded");
    BaseProtectedResourceDetails prd = new BaseProtectedResourceDetails();
    prd.setId("oauth");
    prd.setConsumerKey(consumerKey);
    prd.setSharedSecret(new SharedConsumerSecretImpl(sharedSecret));
    prd.setAdditionalParameters(params);
    prd.setAdditionalRequestHeaders(headers);
    prd.setAdditionalRequestHeaders(additionalparam);
    OAuthRestTemplate restTemplate = new OAuthRestTemplate(prd);


    ResponseEntity<String> response = restTemplate.postForEntity(url,additionalparam,String.class);
    System.out.println("response >>>>> "+response.toString());

    String str = new String(response.toString());
    int jsonStartindex = str.indexOf("[");
    int jsonEndIndex = str.indexOf("]");
    String jsonval = str.substring(jsonStartindex, jsonEndIndex+1);
    System.out.println("jsonval");
    System.out.println(jsonval.toString());
    //JSONObject jsonObj = new JSONObject(jsonval);
    JSONArray jsonArray = new JSONArray(jsonval); 
    System.out.println(jsonArray.toString());
    return response;
}


/*
 * public static String convert(InputStream inputStream) throws IOException {
 * Charset charset=Charset.forName("UTF-8"); return
 * IOUtils.toString(inputStream, charset); }
 */

private static String getNonce()
{
    return RandomStringUtils.randomAlphanumeric(6);
}

/**
 * Generates an integer representing the number of seconds since the unix epoch using the
 * date/time the request is issued
 * 
 * @return  A timestamp for the request
 */
private static String getTimestamp()
{    
    return Long.toString((System.currentTimeMillis() / 1000));
}

private static String hmacSha1(String value, String key)
        throws UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {
    String type = "HmacSHA1";
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
    Mac mac = Mac.getInstance(type);
    mac.init(secret);
    byte[] bytes = mac.doFinal(value.getBytes());
    return bytesToHex(bytes);
}

private final static char[] hexArray = "0123456789abcdef".toCharArray();

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
        v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

我想发送带有参数check bodyParams的发布请求。但是我收到了未经授权的错误401 ,但是邮递员可以正常工作。

1 个答案:

答案 0 :(得分:0)

服务器将向您返回401码,这意味着它需要授权-用户名/密码或令牌或其他东西。