I create httpClient and set settings
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setContentCharset("UTF-8");
First request (get)
GetMethod first = new GetMethod("http://vk.com");
int returnCode = client.executeMethod(first);
BufferedReader br = null;
String lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
first.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(first.getResponseBodyAsStream(), Charset.forName("windows-1251")));
String readLine = "";
while (((readLine = br.readLine()) != null)) {
lineResult += readLine;
}
}
Response correct.
Second request (post):
PostMethod second = new PostMethod("http://login.vk.com/?act=login");
second.setRequestHeader("Referer", "http://vk.com/");
second.addParameter("act", "login");
second.addParameter("al_frame", "1");
second.addParameter("captcha_key", "");
second.addParameter("captcha_sid", "");
second.addParameter("expire", "");
second.addParameter("q", "1");
second.addParameter("from_host", "vk.com");
second.addParameter("email", email);
second.addParameter("pass", password);
returnCode = client.executeMethod(second);
br = null;
lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
second.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(second.getResponseBodyAsStream()));
String readLine = "";
while (((readLine = br.readLine()) != null)) {
lineResult += readLine;
}
}
this response is correct too, but I need to be redirected to Headers.Location.
I do not know how to get value from Headers Location or how to automatically enable redirection.
Due to design limitations HttpClient 3.x is unable to automatically handle redirects of entity enclosing requests such as POST and PUT. You either have to manually convert POST request to a GET upon redirect or upgrade to HttpClient 4.x, which can handle all types of redirects automatically.
In case of the 3.x version of HttpClient, you can also check if the response code is 301 or 302 and then use the Location header to re-post:
client.executeMethod(post);
int status = post.getStatusCode();
if (status == 301 || status == 302) {
String location = post.getResponseHeader("Location").toString();
URI uri = new URI(location, false);
post.setURI(uri);
client.executeMethod(post);
}
You just need to add this:
second.setFollowRedirects(true);
Also, you may use LaxRedirectStrategy
Related
I am making desktop app in java for instagram right now and i don't know how to get code from callback url. My app is desktop so my REDIRECT-URI is http://instagram.com. So in my app i send a request to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code and get redirected to instagram.com?code=CODE. And also forgot to mention, I get a code once by my hands a i gave all permissions. So now then i make request i redirected straightly to URL with code.
How do i get code from callback uri in program in java? This is my code:
static void GetCode()
{
try {
String url = "https://api.instagram.com/oauth/authorize/?client_id=" + ClientId + "&redirect_uri=" + BackUri + "&response_type=code&scope=likes+comments+relationships";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
catch(Exception e)
{
System.out.print("GET CODE ERROR->"+e.toString());
}
}
Change REDIRECT_URI to http://localhost. So the actual 'redirection' code should be done on your side. And you can parse value of argument code. Also look at the answers to this question. This will help you to grab URI with the code.
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 have an app running on J2ME that needs to access the Instagram API. Specifically, I need to post a comment. This is a Post method. So I try to add the "text" parameter to the body of the request by using HttpConnection.setRequestProperty(), but this doesn't seem to work, as Instagram doesn't recognize that the parameter is present. I think this method is failing to write the parameter to the body of the Http request. Any idea how I can make this work in j2me?
Here's my code:
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] response = null;
HttpConnection connection = null;
String url = "";
try {
url = "https://api.instagram.com/v1/media/" + mediaId + "/comments?access_token="+InstagramAPIUtil.accessTokenTest;// POST
url = Util.urlEncodeSpaces(url);
System.out.println(url);
connection = (HttpConnection)Connector.open(url,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("text", comment);
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
is = connection.openInputStream();
if (is != null) {
int ch = -1;
while ((ch = is.read()) != -1) {
bos.write(ch);
}
response = bos.toByteArray();
}
System.out.println("response: "+new String(response));
System.out.println("request: "+connection.getRequestProperty("text"));
return true;
}
And here's what I'm getting back from Instagram:
{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"Missing 'text'"}}
I have not much experience in the HTTP area, but I think you need to write to the output stream that you can get from connection. I don't see where in your code you send actual data.
HttpURLConnection c = (HttpURLConnection) new URL("").openConnection();
OutputStream out = c.getOutputStream();
InputStream in = c.getInputStream();
I am trying to fetch videos from MY OWN YouTube account, so that I get the keywords/tags for each video. I'm trying to use the most simple approach for making an authenticated call to get my videos with keywords/tags.
Here is my Java code:
String clientID = "XXXXXXXXXXXX.apps.googleusercontent.com";
String devKey = "MY-DEVELOPER-KEY";
String userEmail = "MY-GMAIL-EMAIL";
String userPassword = "MY-GMAIL-PASSWORD";
String authorName = "MY-YOUTUBE-ACCOUNT-NAME";
String url = "https://gdata.youtube.com/feeds/api/videos";
YouTubeService service = new YouTubeService( clientID, devKey );
service.setUserCredentials( userEmail, userPassword );
YouTubeQuery query = new YouTubeQuery( new URL( url ) );
query.setAuthor( authorName );
VideoFeed videoFeed = service.query( query, VideoFeed.class );
Please, help me understand what I am doing wrong, to authenticate and get those media keywords.
If you are going to refer me to another authentication option, please, show an example of using that other option for my specific scenario.
You're running into the behavior described in this blog post: your API calls are going against the search index, and those results will never have the keywords in them.
There's an example that shows how you could request the uploads feed in Java using v2 of the Data API; you can modify that example to use the channel name default instead of username and you'll automatically pull in the uploads feed for the currently authenticated account.
Here is what finally worked for me to get JSON-C feed with tags (keywords):
/** AUTHENITICATION **/
// HTTP connection
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Form the POST parameters
StringBuilder content = new StringBuilder();
content.append("Email=").append(URLEncoder.encode("MY-GMAIL-LOGIN", "UTF-8"));
content.append("&Passwd=").append(URLEncoder.encode("MY-GMAIL-PASSWORD", "UTF-8"));
content.append("&service=").append(URLEncoder.encode("youtube", "UTF-8"));
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.toString().getBytes("UTF-8"));
outputStream.close();
// Check response status
int responseCode = urlConnection.getResponseCode();
if( responseCode != HttpURLConnection.HTTP_OK ) {
// EXCEPTION
}
// Get the token from the response
String token;
InputStream inputStream = urlConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = in.readLine()) != null) {
if ( line.indexOf("Auth=") > -1 ) {
token = line.split("=")[1];
}
}
/** JSON-C FEED WITH TAGS **/
HttpClient client = new HttpClient();
GetMethod method = new GetMethod("http://gdata.youtube.com/feeds/api/users/default/uploads?v=2&alt=jsonc&max-results=50&start-index=1");
// set the authentication headers
method.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
method.setRequestHeader("X-GData-Key", "key=MY-DEV-KEY");
method.setRequestHeader("GData-Version", "2");
method.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
// Make the call
int statusCode = client.executeMethod(method);
if ( statusCode != HttpStatus.SC_OK ) {
// EXCEPTION
}
String JSON = method.getResponseBodyAsString();
I noticed a strange phenomenon when using the apache httpclient libraries and I want to know why it occurs. I created some sample code to demonstrate.
Consider the following code:
//Example URL
String url = "http://www.amazon.com/gp/offer-listing/05961580/ref=dp_olp_used?ie=UTF8";
GetMethod get = new GetMethod(url);
HttpMethodRetryHandler httpHandler = new DefaultHttpMethodRetryHandler(1, false);
get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpHandler );
get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
HttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
HttpClient client = new HttpClient( connectionManager );
client.getParams().setParameter("http.useragent", FIREFOX );
String line;
StringBuilder stringBuilder = new StringBuilder();
String toStreamBody = null;
String toStringBody = null;
try {
int statusCode = client.executeMethod(get);
if( statusCode != HttpStatus.SC_OK ){
System.err.println("Internet Status: " + HttpStatus.getStatusText(statusCode) );
System.err.println("While getting page: " + url );
}
//toString
toStringBody = get.getResponseBodyAsString();
//toStream
InputStreamReader isr = new InputStreamReader(get.getResponseBodyAsStream())
BufferedReader rd = new BufferedReader(isr);
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
} catch (java.io.IOException ex) {
System.out.println( "Failed to get page: " + url);
} finally {
get.releaseConnection();
}
toStreamBody = stringBuilder.toString();
This code prints nothing:
System.out.println(toStringBody); // ""
This code prints the web page:
System.out.println(toStreamBody); // "Whole Page"
But it gets even stranger...
Replace:
get.getResponseBodyAsString();
With:
get.getResponseBodyAsString(150000);
Now we get the error:
Failed to get page: http://www.amazon.com/gp/offer-listing/0596158068/ref=dp_olp_used?ie=UTF8
I was unable to find another website besides for amazon that replicates this behavior but I assume there are others.
I am aware that according to the documentation at http://hc.apache.org/httpclient-3.x/performance.html discourages the use of getResponseBodyAsString(), it does not say that the page will not load, only that you may be at risk of an out of memory exception. Is it possible that getResponseBodyAsString() is returning the page before it loads? Why does this only happen with amazon?
Did you test with any other URL?
The URL in code that you provided redirects with 302 to http://www.amazon.com/dp/05961580/?tag=stackoverfl08-20, which then returns 404 (not found).
HttpClient does not handle redirects: http://hc.apache.org/httpclient-3.x/redirects.html