I'm new to mobile apps development. I'm developing a blackberry application which reads tweets from the user's timeline. So far I managed to get the OAuth access token. The problem happens when I try to use this access token to read the tweets I get a 401 response with a message "Unauthorized". I'm not using any libraries I'm doing everything on my own. Could anyone help me with this?
Thanks,
Here's the code:
HttpConnectionFactory factory = new HttpConnectionFactory( url,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length", Integer.toString(header.getBytes().length));
os = httpConn.openOutputStream();
os.write(header.getBytes());
os.close();
os = null;
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
// Dialog.alert(httpConn.getDate()+" : "+System.currentTimeMillis());
if (resp == HttpConnection.HTTP_OK) {
XMLReader parser;
try {
parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
parser.parse(new InputSource(input));
for(int i=0 ; i<2 ; i++)
{
tweets.addElement( parser.getProperty("text").toString());
Dialog.alert(parser.getProperty("text").toString());
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dialog.alert("your tweet was posted successfully :)");
}
Dialog.alert(httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
return (httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not an expert in OAuth, however just a note:
This:
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
and this:
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
are mutually exclusive things. You are posting data to server, so it should be a POST (not GET).
Related
So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();
my program crash when user inserts a weird url
It should go like
while(condition) {
try {
String url = reciveURL();
Document rss = Jsoup.connect( url ).get();
}
catch (MalformedURLException e) {
System.err.println("Invalid URL");
} catch (OthersExceptions e){
Others.Actions();
}
}
The problem is, this throws "java.net.MalformedURLException: no protocol", instead of printing "Invalid URL" and the program crash (when user inserts any other kind of text)
Thanks!
Lol, solved myself, but i'll let the question as theres no post on the same issue
You should import java.net.url, this brings the "URL" type, which triggers the MalformedURLException (Jsoup doesnt do this)
So it goes like this
while(true){
{
String url = reciveURL() ;
URL chk_url = new URL(url);
Document rss = Jsoup.connect( url ).get();
} catch (MalformedURLException e) {
System.err.println("url mal puesta!");
}
}
How can I know the date a webpage last-modified using Android Java? or how I can request for
If-Modified-Since: Allows a 304 Not Modified to be returned if content is unchanged
using http headers?
I could do it this way:
URL url = null;
try {
url = new URL("http://www.example.com/example.pdf");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection httpCon = null;
try {
httpCon = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long date = httpCon.getLastModified();
I have the following on a web servlet:
EDITED:
public String tryGoogleAuthentication(String auth_token){
HttpURLConnection connection = null;
try {
//connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2v1/tokeninfo?access_token={"+auth_token+"}")).openConnection();
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/user info")).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer {"+auth_token+"}");
connection.setRequestProperty("Host", "googleapis.com");
//read response
String response = fromInputStreamToString(connection.getInputStream());
System.out.println(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return CONST.STATUS_OK;
}
In android:
private void googleAuthenticate(){
try {
mOAauthHelper = new OAuthHelper("something.net", "xxxxxxxxxx",
"https://www.googleapis.com/auth/userinfo.profile", "alex://myScheme");
String uri = mOAauthHelper.getRequestToken();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
//Intent i = new Intent(this, GoogleOAUTHActivity.class);
//i.putExtra(GoogleOAUTHActivity.GOOGLE_OAUTH_ENDPOINT_KEY, uri);
//startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
}
}
and
#Override
protected void onNewIntent(Intent intent) {
//super.onNewIntent(intent);
Uri uri = intent.getData();
String oauthToken = uri.getQueryParameter("oauth_token");
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
if(oauthToken != null){
authorizeGoogleSessionToServer(oauthToken);
}
}
After this, I send the request token to my servlet where I tried to get user profile, but with no success.
Could you please tell me what's wrong and why I'm getting error 400 from google?
Thanks.
Unfortunately, I can see a few issues with this already
you should never have curly braces in your URL or even in the Bearer header as stated in the draft.
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/userinfo?access_token={"+auth_token+"}")).openConnection()
400 means that you're missing something in your request, there is probably more information about it in the same response as specific error node.
Finally, take care, oauth_verifier param is from OAuth 1.
I suggest you test your request URL's, using the Google OAuth2 playground
Good luck!
I got some code from java httpurlconnection cutting off html and I am pretty much the same code to fetch html from websites in Java.
Except for one particular website that I am unable to make this code work with:
I am trying to get HTML from this website:
http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289
But I keep getting junk characters. Although it works very well with any other website like http://www.google.com.
And this is the code that I am using:
public static String PrintHTML(){
URL url = null;
try {
url = new URL("http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6");
try {
System.out.println(connection.getResponseCode());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String html = builder.toString();
System.out.println("HTML " + html);
return html;
}
I don't understand why it doesn't work with the URL that I mentioned above.
Any help will be appreciated.
That site is incorrectly gzipping the response regardless of the client's capabilities. Normally a server should only gzip the response whenever the client supports it (by Accept-Encoding: gzip). You need to ungzip it using GZIPInputStream.
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));
Note that I also added the right charset to the InputStreamReader constructor. Normally you'd like to extract it from the Content-Type header of the response.
For more hints, see also How to use URLConnection to fire and handle HTTP requests? If all what you after all want is parsing/extracting information from the HTML, then I strongly recommend to use a HTML parser like Jsoup instead.