I have problem with authentication GReader editing API. I can do the HTTPS (https://www.google.com/accounts/ClientLogin) for authentication and google is returning three tokens (SID, LSID, AUTH), but no HSID.
When I try add a new feed http://www.google.com/reader/api/0/subscription/quickadd?ck=1290452912454&client=scroll with POST data T=djj72HsnLS8293&quickadd=blog.martindoms.com/feed/ without HSID in Cookie, is response status code 401. With SID and HSID in Cookie everything works properly.
What is and where can I find this HSID string?
Thaks for your answers.
My code:
public void addNewFeed() throws IOException {
HttpPost requestPost = new HttpPost("http://www.google.com/reader/api/0/subscription/quickadd?ck=1290452912454&client=scroll");
getSid();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DefaultHttpClient client = new DefaultHttpClient();
requestPost.addHeader("Cookie", "SID=" + _sid + "; HSID=" + _hsid);
try {
nameValuePairs.add(new BasicNameValuePair("T", _token));
nameValuePairs.add(new BasicNameValuePair("quickadd", "blog.martindoms.com/feed/"));
requestPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(requestPost);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
System.out.println(str.toString());
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Looks like you might be using old info as a reference. Google switched to using auth now.
You'll need to replace getSid() with a getAuth() function.
Then this line
requestPost.addHeader("Cookie", "SID=" + _sid + "; HSID=" + _hsid);
should now be this
requestPost.addHeader("Authorization", "GoogleLogin auth=" + _auth);
Related
I have the following code to connect from my android application to zappos api server and search for some stuff. But It either returns error 404 or We are unable to process the request from the input feilds given.
When I execute the same query it works on the web browser.
The query is:
http://api.zappos.com/Search&term=boots&key=<my_key_inserted_here>
Code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://api.zappos.com/Search");
NameValuePair keypair = new BasicNameValuePair("key",KEY);
NameValuePair termpair = new BasicNameValuePair("term",data);
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(keypair);
params.add(termpair);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
String str;
StringBuilder sb = new StringBuilder();
HttpEntity entity =response.getEntity();
if (entity != null) {
DataInputStream in = new DataInputStream(entity.getContent());
while (( str = in.readLine()) != null){
sb.append(str);
}
in.close();
}
Log.i("serverInterface","response from server is :"+sb.toString());
What am I doing wrong?
If I am correct, what you want to do is a GET request with parameters.
Then,the code would looks like something like that:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://api.zappos.com/Search");
HttpParams params = new BasicHttpParams();
params.setParameter("key", "KEY");
params.setParameter("term", "data");
get.setParams(params);
HttpResponse response;
response = client.execute(get);
String str;
StringBuilder sb = new StringBuilder();
HttpEntity entity = response.getEntity();
if (entity != null) {
DataInputStream in;
in = new DataInputStream(entity.getContent());
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
}
Log.i("serverInterface", "response from server is :" + sb.toString());
I found an answer to the question based on ALL of your help. I got the hint that I must search how to connect to REST service and I also used this result. This is the exact result I was looking for. Sadly it resembles too much to what I'm trying to achieve that I think whoever asked it might be applying to the same position :(
I am trying to send data to a server as POST data. I have 3 fields, one is a String, another is a TIMEDATE and the last is a BLOB.
I have been trying the following code but it doesn't seem to work. I can't turn the byte array into a String and I am unsure how to append the byte array as a parameter.
If anybody has an idea I would appreciate to hear from you !
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://127.0.0.1/add_new_profile");
ProfileData profileData = getProfileData();
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name",profileData.getName()));
nameValuePairs.add(new BasicNameValuePair("created",profileData.getTimeCreated()));
nameValuePairs.add(new BasicNameValuePair("profile_data",new String(profileData.getDataAsByteArray())));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Server PHP script:
<?php
include('connect_db.php');
include('tools.php');
$name = $_POST['name'];
$created = $_POST['created'];
$profile_data = $_POST['profile_data'];
$query = "INSERT INTO fingerprint_profiles(name,created,fingerprint) VALUES ('".$name."','".$created"','".$fingerprint_data."')";
$result = mysql_query($query);
print_as_json($result);
?>
I'm currently trying to upload to imgur using their current API v3, however I keep getting the error
error: javax.net.ssl.SSLException: hostname in certificate didn't match: api.imgur.com != imgur.com OR imgur.com
The error is pretty self-explaintory so I thought I would try using http instead but I get the error code 400 with imgur. I am not sure if this means how I am trying to upload is wrong or if Imgur doesn't like not SSL connections.
Below is my module of code connecting to Imgur:
public String Imgur (String imageDir, String clientID) {
//create needed strings
String address = "https://api.imgur.com/3/image";
//Create HTTPClient and post
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
//create base64 image
BufferedImage image = null;
File file = new File(imageDir);
try {
//read image
image = ImageIO.read(file);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArray);
byte[] byteImage = byteArray.toByteArray();
String dataImage = new Base64().encodeAsString(byteImage);
//add header
post.addHeader("Authorization", "Client-ID" + clientID);
//add image
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("image", dataImage));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute
HttpResponse response = client.execute(post);
//read response
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String all = null;
//loop through response
while (rd.readLine() != null) {
all = all + " : " + rd.readLine();
}
return all;
}
catch (Exception e){
return "error: " + e.toString();
}
}
I hope someone can help in either finding the error in the above code or explaining how to fix the current HTTPS issue, thanks.
It looks like the domain name in the certificate does not match the domain name that you are accessing, so SSL is failing as expected. You can tell HttpClient to ignore the certificate problem and just establish the connection. See this stackoverflow answer for details.
I am attempting to write an Android app which will allow me to read text from a website that holds my work roster https://www.blahblahblahcompany.com/Rostering/exportRoster.aspx
Is this possible? Would I be able to authenticate myself with the website and then download the source code?
The website in question also has the ability to export the roster as an .xls file
screenshot of the page in question
http://img528.imageshack.us/img528/9954/rosterf.png
I don't know if I've get what you really want to do, but I'm sure that at least, you gonna need some Get/Post operations to execute authentication proccess and retrieve data/informations. Please check the following methods:
public StringBuilder post(String url, List<NameValuePair> nvps) {
try {
HttpPost httppost = new HttpPost(url);
// if there is cookies, set then
if (cookies != null && cookies.size() > 0) {
String cookieString = "";
for (int i = 0; i < cookies.size(); ++i) {
cookieString += cookies.get(i).getName() + "=" + cookies.get(i).getValue() + "; ";
}
cookieString += "domain=" + Constants.BaseUrl + "; " + "path=/";
httppost.addHeader("Cookie", cookieString);
}
// connection timeout options
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, Constants.timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, Constants.timeoutSocket);
// setup the post method
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpClient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;)
builder.append(line).append("\n");
// set cookies
List<Cookie> incomingCookies = httpClient.getCookieStore().getCookies();
for (int i = 0; incomingCookies != null && i < incomingCookies.size(); i++) {
cookies.add(incomingCookies.get(i));
}
return builder;
} catch (UnsupportedEncodingException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
}
return null;
}
The above mehod executes a post in the url string parameter, using the pair values nvps as arguments for header. Note that Constants class is the class where you are declaring static strings (such as API entries) for your WebService, and the field cookies is a list of Cookies that gonna hold your session issues. This method will return the result for your POST request as a string builder object. Basically, it is a general-purpose method that can be used in several cases, and you should do little adaptations to fit tasks. This is what you can use to authenticate.
There is another important method, the Http GET:
public StringBuilder get(String url) {
try {
HttpGet httpget = new HttpGet(url);
// if there is cookies, set then
if (cookies != null && cookies.size() > 0) {
String cookieString = "";
for (int i = 0; i < cookies.size(); ++i) {
cookieString += cookies.get(i).getName() + "=" + cookies.get(i).getValue() + "; ";
}
cookieString += "domain=" + Constants.BaseUrl + "; " + "path=/";
httpget.addHeader("Cookie", cookieString);
}
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, Constants.timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, Constants.timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpget);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;)
builder.append(line).append("\n");
// set cookies
List<Cookie> incomingCookies = httpClient.getCookieStore().getCookies();
for (int i = 0; incomingCookies != null && i < incomingCookies.size(); i++) {
cookies.add(incomingCookies.get(i));
}
return builder;
} catch (UnsupportedEncodingException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
}
return null;
}
This one do similar sequence of steps, but with very different purposes. The goal of this one is to retrieve informations, considering that you already have authenticated or that the auth process is not needed. It returns the requested data as a string builder.
Please, note that besides these methods are very general, you must closely check what is the proccess used in your requested web page. Hope that it helps you in some way! ;-)
In the Android web browser, go to Tools > Options > Encryption > View Certificates to see a list of supported certificate providers. As long as you buy a cert from a supported provider you will be able to do it. Here is a stack answer that might have some clues.
So I have 2 codes which supposedly do the same. The one I'm using on Android however, returns the wrong HTML data. The stock Java one returns the correct data after sending the request. I have both codes here. Can you tell me (EVEN THOUGH I GAVE INTERNET PERMISSION TO ANDROID) why the Android one isn't working, while the stock Java one is working? This is the Android code:
EDIT: I FOUND THE FIX. If you're going to use a StringEntity to send such a String to the Server, you have to set the content to application/x-www-form-urlencoded. I've edited my code to show this:
public static String sendNamePostRequest(String urlString) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
StringEntity se = new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3");
se.setContent("application/x-www-form-urlencoded");
post.setEntity();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
This is the stock Java code:
public String sendNamePostRequest(String urlString) {
StringBuffer sb = null;
try {
String data = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3";
// String data = "";
URL requestUrl = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) requestUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(data);
dos.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String in = "";
sb = new StringBuffer();
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
dos.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
If the data is getting to the server, you might want to see what is happening there (logs, errors, exceptions, etc.) Other than that:
use can use HttpURLConnection, so you can have the exact same code
For HttpClient, not sure whey you are encoding the entity yourself. Use NameValuePair to set parameters, and HttpClient will encode them for you (correctly).
You can use NameValuePair and UrlEncodedFormEntity:
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(KEY1, VALUE1));
nvps.add(new BasicNameValuePair(KEY2, VALUE2));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.setEntity(p_entity);