title: 401 Failed to validate oauth signature and token (https://api.twitter.com/oauth/request_token) (Java code)
body: <p>I try to get oauth_token from twitter api but get exception:<br>
  <code>java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.twitter.com/oauth/request_token</code><br>
  <br>
  <strong>Error stream get:</strong><br>
  <em>Failed to validate oauth signature and token</em><br>
  <br>
  <strong>Here is a signatureBaseString, signature and Authorization header example :</strong><br>
  <strong><em>signatureBaseString</em></strong>: POST&amp;https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&amp;oauth_callback%3Dhttp%253A%252F%252F127.0.0.1%253A8080%252Ftwlogin%26oauth_consumer_key%3D2YhNLyum1VY10UrWBMqBnatiT%26oauth_nonce%3D1413642155863%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1413642155%26oauth_version%3D1.0<br><br>
  <strong><em>oAuthSignature:</em></strong> +Ov4WEws5XULVIxx9n/Q9ybzlrM=<br><br>
  <strong><em>authorizationHeaderValue:</em></strong> OAuth oauth_callback="http%3A%2F%2F127.0.0.1%3A8080%2Ftwlogin", oauth_consumer_key="2YhNLyum1VY10UrWBMqBnatiT", oauth_nonce="1413642155863", oauth_signature="%2BOv4WEws5XULVIxx9n%2FQ9ybzlrM%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1413642155", oauth_version="1.0"<br><br></p>
  
  <p><strong>Here is a code:</strong><br> 
  <em>NameValuePair comparator:</em><br></p>
  
  <pre><code>class NvpComparator implements Comparator&lt;NameValuePair&gt; {
          @Override
          public int compare(NameValuePair arg0, NameValuePair arg1) {
              String name0 = arg0.getName();
              String name1 = arg1.getName();
              return name0.compareTo(name1);
          }
      }
  </code></pre>
  
  <p><em>URL encode</em></p>
  
  <pre><code>class OAuth{
  ...
      public static String percentEncode(String s) {
              return URLEncoder.encode(s, "UTF-8")
                      .replace("+", "%20").replace("*", "%2A")
                      .replace("%7E", "~");
      }
  ...
  }
  </code></pre>
  
  <p><em>Request method</em></p>
  
  <pre><code>public String twAuth() {
              String method = "POST";
              String url = "https://api.twitter.com/oauth/request_token";
              String oAuthConsumerKey = "2YhNLyum1VY10UrWBMqBnatiT";
              String oAuthConsumerSecret = ***CONSUMER_SECRET***;
              String oAuthCallback = "http://127.0.0.1:8080/twlogin";
              String oAuthNonce = String.valueOf(System.currentTimeMillis());
              String oAuthSignatureMethod = "HMAC-SHA1";
              String oAuthTimestamp = String.valueOf(System.currentTimeMillis() / 1000);
              String oAuthVersion = "1.0";
  
              List&lt;NameValuePair&gt; allParams = new ArrayList&lt;NameValuePair&gt;();
              allParams.add(new BasicNameValuePair("oauth_callback", oAuthCallback));
              allParams.add(new BasicNameValuePair("oauth_consumer_key", oAuthConsumerKey));
              allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
              allParams.add(new BasicNameValuePair("oauth_signature_method", oAuthSignatureMethod));
              allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
              allParams.add(new BasicNameValuePair("oauth_version", oAuthVersion));
  
              Collections.sort(allParams, new NvpComparator());
  
              StringBuffer params = new StringBuffer();
              for(int i=0;i&lt;allParams.size();i++)
              {
                  NameValuePair nvp = allParams.get(i);
                  if (i&gt;0) {
                      params.append("&amp;");
                  }
                  params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
              }
  
              String signatureBaseStringTemplate = "%s&amp;%s&amp;%s";
              String signatureBaseString =  String.format(signatureBaseStringTemplate,
                      OAuth.percentEncode(method),
                      OAuth.percentEncode(url),
                      OAuth.percentEncode(params.toString()));
  
              String signatureKey = OAuth.percentEncode(oAuthConsumerSecret)+"&amp;";
  
          SecretKeySpec signingKey = new SecretKeySpec(signatureKey.getBytes(), "HmacSHA1");
              Mac mac = Mac.getInstance("HmacSHA1");
              mac.init(signingKey);
              byte[] rawHmac = mac.doFinal(signatureBaseString.getBytes());
              String oAuthSignature = new String(Base64.encodeBase64(rawHmac));
  
          String authorizationHeaderValueTempl = "OAuth oauth_callback=\"%s\", " +
                      "oauth_consumer_key=\"%s\", " +
                      "oauth_nonce=\"%s\", " +
                      "oauth_signature=\"%s\", " +
                      "oauth_signature_method=\"%s\", " +
                      "oauth_timestamp=\"%s\", " +
                      "oauth_version=\"%s\"";
  
              String authorizationHeaderValue =String.format(authorizationHeaderValueTempl,
                      OAuth.percentEncode(oAuthCallback),
                      OAuth.percentEncode(oAuthConsumerKey),
                      OAuth.percentEncode(oAuthNonce),
                      OAuth.percentEncode(oAuthSignature),
                      OAuth.percentEncode(oAuthSignatureMethod),
                      OAuth.percentEncode(oAuthTimestamp),
                      OAuth.percentEncode(oAuthVersion));
  
          URL obj = new URL(url);
          HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
  
          con.setRequestMethod("POST");
          con.setRequestProperty("Authorization", authorizationHeaderValue);
  
          con.setDoOutput(true);
  
          int responseCode = con.getResponseCode();
          BufferedReader in = new BufferedReader(
                  new InputStreamReader(con.getInputStream()));
          String inputLine;
          StringBuffer response = new StringBuffer();
  
          while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
          }
          in.close();
  
          System.out.println(response.toString());
  
          return "aboutas";
      }
  </code></pre>
  
  <p><br>
  <strong>Here is a twitter application settings:</strong><br>
  <strong><em>Consumer Key (API Key):</em></strong> 2YhNLyum1VY10UrWBMqBnatiT<br>
  <strong><em>Callback URL:</em></strong> <code>http://127.0.0.1:8080/twlogin</code><br>
  <strong><em>Sign in with Twitter:</em></strong> Yes<br>
  <strong><em>Website:</em></strong> <code>http://127.0.0.1:8080</code><br></p>
  
  <p>Can anybody help me? I don't know what to do..</p>