向Twitter的REST API v1.1发送请求时出错

时间:2013-06-13 15:08:04

标签: android twitter http-post

我已经尝试了几天让我的应用以某种方式连接到Twitter的休息api v 1.1,但几乎没有任何效果,或者我无法很好地适应它的工作,两者之一。我找到了一个教程,解释了Twitter开发者网站的代码,我试图为我的应用程序实现它,但它一直给我一个错误的错误,使用以下文本“api.twitter.com”。我不知道它是什么类型的错误,但我认为它是关于http请求的东西,因为我看到它没有通过这行代码“HttpResponse response = client.execute(post);”。我希望我能得到一些反馈,或者一些想法我真的有点麻烦。提前谢谢。

这是代码:

  package com.gtware.android.twitter.restapi;

  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.io.UnsupportedEncodingException;
  import java.net.URLEncoder;
  import java.util.Date;
  import java.util.UUID;

  import javax.crypto.Mac;
  import javax.crypto.spec.SecretKeySpec;

  import org.apache.http.HttpResponse;
  import org.apache.http.client.HttpClient;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.methods.HttpRequestBase;
  import org.apache.http.entity.StringEntity;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONException;
  import org.json.JSONObject;

  import android.app.Activity;
  import android.app.AlertDialog;
  import android.os.Bundle;
  import android.text.Editable;
  import android.text.TextWatcher;
  import android.util.Base64;
  import android.util.Log;
  import android.view.View;
  import android.widget.Button;
  import android.widget.EditText;

 public class PostActivity extends Activity {

 public static final String ENCODING = "UTF-8";
 private static final String postURL = "https://api.twitter.com/1.1/statuses/update.json";

   / /Keys & Secrets
   private static final String consumerKey = "this is where i enter my consumer key ";
   private static final String consumerSecret = "this is where i enter my consumer secret ";
   private static final String accessToken = "this is where i enter my accestoken";
   private static final String accessTokenSecret = "this is where i enter my accestokenSecret";

   //OAuth Header Keys
   private static final String oauth_consumer_key = "oauth_consumer_key";
   private static final String oauth_nonce = "oauth_nonce";
   private static final String oauth_signature = "oauth_signature";
   private static final String oauth_signature_method = "oauth_signature_method";
   private static final String oauth_timestamp = "oauth_timestamp";
   private static final String oauth_token = "oauth_token";
   private static final String oauth_version = "oauth_version";
   private static final String status = "status";
   private static final String include_entities="include_entities";
   private static final String x="true";
   private EditText tweetEditor;
   private Button postButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.post_main);
    postButton = (Button)findViewById(R.id.postButton);
    tweetEditor = (EditText)findViewById(R.id.tweetEditor);
    tweetEditor.addTextChangedListener(new TextWatcher() {
     public void onTextChanged(CharSequence s, int start, int before, int count) {
      if(tweetEditor.getText().length() == 0) {
       postButton.setEnabled(false);
      }
      else {
       postButton.setEnabled(true);
      }
     }
     public void beforeTextChanged(CharSequence s, int start, int count,
 int after) { }

     public void afterTextChanged(Editable s) { }
    });
      }

      private void alertUser(String str) {
       new AlertDialog.Builder(this)
      .setMessage(str)
      .setNeutralButton("OK", null)
      .show();
}

public void post(View button) {
 HttpClient client = new DefaultHttpClient();
 HttpPost post = new HttpPost(postURL);
 try {
  String message = tweetEditor.getText().toString();
  addAuthorizationHeader(message, post);
  post.setEntity(new StringEntity(percentEncode(status) + "=" + percentEncode(message)));

  HttpResponse response = client.execute(post);

  parsePostResponse(response);
 }
 catch(Exception e) {
  Log.e(PostActivity.class.getName(), e.getMessage());
  alertUser("Error: " + e.getMessage());
 }
}

private void addAuthorizationHeader(String tweet, HttpRequestBase request) throws Exception {
 request.setHeader("Content-Type", "application/x-www-form-urlencoded");

 String nonce = base64Encode((UUID.randomUUID().toString().replaceAll("-", "").replace("=","").getBytes()));
 nonce=nonce.substring(0, nonce.length()-1);
    String signatureMethod = "HMAC-SHA1";
    String timeStamp = String.valueOf(new Date().getTime() / 1000);
    String version = "1.0";

    //Generating the Parameter String:
    //Add request parameters and status message alphabetically (DO NOT ADD SIGNATURE)
    //Encode keys and values while adding
    //Insert = character between each key and its value
    //Add an ampersand (&) to the end if there are more parameters
    String parameterString = 
      percentEncode(include_entities)+"="+percentEncode(x)+"&"+
       percentEncode(oauth_consumer_key) + "=" + percentEncode(consumerKey) + "&" +
       percentEncode(oauth_nonce) + "=" + percentEncode(nonce) + "&" +
       percentEncode(oauth_signature_method) + "=" + percentEncode(signatureMethod) + "&" +
       percentEncode(oauth_timestamp) + "=" + percentEncode(timeStamp) + "&" +
       percentEncode(oauth_token) + "=" + percentEncode(accessToken) + "&" +
       percentEncode(oauth_version) + "=" + percentEncode(version) + "&" +
       percentEncode(status) + "=" + percentEncode(tweet);
    Log.e("This is the parameterString",parameterString);
    Log.e("This is the nonce  variable",nonce);
    //Generate the SignatureBaseString
    String signatureBaseString = "POST&" + percentEncode(postURL) + "&" + percentEncode(parameterString);
     Log.e("Signature base looks like this ",signatureBaseString);
    //Generate the SigningKey
    String signingKey = percentEncode(consumerSecret) + "&" + percentEncode(accessTokenSecret);
    Log.e("Signing key  looks like this ",signingKey);
    //Generate HMAC-MD5 signature
    String signature = generateHmacSHA1(signingKey, signatureBaseString);
    Log.e("Signature looks like  so  ",signature);
    //Build the HTTP Header
    String oauthHeader =
"OAuth " + 
percentEncode(oauth_consumer_key) + "=\"" + percentEncode(consumerKey) + "\", " +  
percentEncode(oauth_nonce) + "=\"" + percentEncode(nonce) + "\", " + 
percentEncode(oauth_signature) + "=\"" + percentEncode(signature) + "\", " + 
   percentEncode(oauth_signature_method) + "=\"" + percentEncode(signatureMethod) + "\", " + 
   percentEncode(oauth_timestamp) + "=\"" + percentEncode(timeStamp) + "\", " + 
   percentEncode(oauth_token) + "=\"" + percentEncode(accessToken) + "\", " + 
   percentEncode(oauth_version) + "=\"" + percentEncode(version) + "\"";
     Log.e("Header looks like this ",oauthHeader);
    request.addHeader("Authorization", oauthHeader);
}

private String generateHmacSHA1(String key, String value) throws Exception {
 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), "HmacSHA1");
 Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(keySpec);
    byte[] result = mac.doFinal(value.getBytes(ENCODING));
    return base64Encode(result);
}

private void parsePostResponse(HttpResponse response) throws IllegalStateException, IOException, JSONException {
 StringBuilder sb = getResponseBody(response);
 if(response.getStatusLine().getStatusCode() == 200) {
  alertUser("Tweet Successful!\nID: " + new JSONObject(sb.toString()).get("id"));
 }
 //Not OK
 else {
  Log.e(PostActivity.class.getName(), "Response Code: " + response.getStatusLine().getStatusCode() + "\nResponse: " + sb.toString());
  alertUser("Error Code: " + response.getStatusLine().getStatusCode() + "\n" + new JSONObject(sb.toString()).getString("error"));
 }
}

      private static StringBuilder getResponseBody(HttpResponse response) throws IllegalStateException, IOException {
       InputStream is = response.getEntity().getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while((line = br.readLine()) != null) {
     sb.append(line);
    }
    br.close();
    return sb;
      }

private String percentEncode(String s) throws UnsupportedEncodingException {
    //This could be done faster with more hand-crafted code.
    return URLEncoder.encode(s, ENCODING)
      // OAuth encodes some characters differently:
            .replace("+", "%20").replace("*", "%2A")
            .replace("%7E", "~");
}

private static String base64Encode(byte[] array) {
 return Base64.encodeToString(array, Base64.NO_WRAP);
}

  }

0 个答案:

没有答案