Download file using REST API - java

I am trying to call a REST API using Java client.
The Rest API https://api.gdc.cancer.gov/data has files data.
When I append file name to the URL (https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c) I can download the given file from using browser.
here filename is 556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c.
can you please let me know,How can i achieve in this JAVA. The code I am using.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class DownloadFilesAPI {
public DownloadFilesAPI() {
super();
}
public static String sendPostRequest(String requestUrl) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("POST");
// connection.connect();
//Get the response status of the Rest API
// int responsecode = connection.getResponseCode();
//System.out.println("Response code is: " +responsecode);
//connection.getResponseMessage();
// System.out.println(connection.getResponseMessage());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
// System.out.println(connection.getResponseMessage());
// System.out.println( JsonPath.from(requestUrl));
OutputStreamWriter writer = new
OutputStreamWriter(connection.getOutputStream());
writer.write(requestUrl);
writer.close();
/* BufferedReader br = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close(); */
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
public static void main(String[] args) {
List<String> values = new ArrayList<>();
// values.add("556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c");
String requestUrl = "https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c";
sendPostRequest(requestUrl);
}
private static String preparePayload(List<String> values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append("\"" + value + "\",");
}
String Requiredvalue = sb.toString().substring(0, sb.toString().length() - 1);
return "{ \"ids\":[" + Requiredvalue + "] } } }";
}
}

You can't just output a String since you are trying to download a pdf. If you simply want to download the File there is an easier method adapted from this answer:
String requestUrl = "https://api.gdc.cancer.gov/data/556e5e3f-0ab9-4b6c-aa62-c42f6a6cf20c";
URL url = new URL(requestUrl);
InputStream in = url.openStream();
Files.copy(in, Paths.get("your_filename.pdf"), StandardCopyOption.REPLACE_EXISTING);
in.close();
System.out.println("finished!");
I have tested it for the URL you provided and got the pdf File without problems.

Related

Send HTTP POST reqeust with Graphql query form java

I want to create a ticket on monday.com. I wrote HTTP method which makes POST call on specific monday server and as a parameter I'm passing graphql query. but unfortunately with no success, I think I'm passing query parameters in a wrong way, but I can't figure what exactly I'm doing wrong.
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Monday {
static int id = 1249501957;
static String token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String query = "mutation {\n"
+ " create_item(item_name:\"heyyyyyyy\", board_id:" + id + "){\n"
+ " id\n"
+ " }\n"
+ "}";
static String targetURL = "https://levank707.monday.com/projects";
public static void main(String[] args) throws Exception {
executePost(targetURL,query);
}
public static String executePost(String targetURL, String query) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/graphql");
connection.setRequestProperty("Content-Length",
Integer.toString(query.getBytes().length));
connection.setRequestProperty("Authorization",token );
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(query);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}}

Unable to unzip the web service response in Linux using java

We are executing web services using java code. The web service response comes in gzip format from the web service provider. We are unzipping the response using GZIPInputStream after receiving the response.
Response is converted into byte codes and then passing as input to gzipinputstream. This code is working fine in Eclipse and able to unzip the response string. The same code is not working in Linux and throwing the error "Not in Gzip format" while passing the byte array to gzipinputstream.
We checked the default charset in Windows is windows-1252 and in Linux is UTF-8. So, we tried to get the bytes in UTF-8 and windows-1252. Both are not working.
Can anyone please help me where is it going wrong and how to resolve the issue?
Tried changing the charset while generating the byte codes of the response.
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.io. * ;
import java.nio.charset.*;
import java.util.zip.GZIPInputStream;
import java.nio.charset.*;
public class WSConnectTest {
public final static String UserName = null; //User id login for Fusion
public final static String instanceURL = null;
public final static String USER_PWD = null; // API key shared by CSOD
private static final String PROXY_URL = null; //UBS proxy URL
private static final int PROXY_PORT = 8080;
private static final String PROXY_USERNAME = "USER_NAME";
private static final String PROXY_PASSWORD = "PASSWORD";
final static String USER_AGENT = "Mozilla/5.0";
static Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
PROXY_URL, PROXY_PORT));
static {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(UserName, USER_PWD.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
public static void main(String[] args) throws Exception {
FusionConnect fusionconnect = new FusionConnect();
String theURL = instanceURL + "<RESOURCE_NAME>";
System.out.println("The URL to be called is : " + theURL);
String json = "<JSON_STRING>"
String post_param = new String(json.toString());
System.out.println("The json is :" + json);
PostRequestWithFilter(theURL, post_param);
}
private static void PostRequestWithFilter(String url, String json) throws Exception {
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection(proxy);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept-Language", "UTF-8");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setDoOutput(true);
con.setConnectTimeout(15000);
System.out.println("get content type :"+con.getRequestProperties());
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("\nResponse Code : " + responseCode);
System.out.println("\nResponse message : " + con.getResponseMessage());
String inputLine;
StringBuffer response = new StringBuffer();
String ResponseStr = null;
byte[] bresponse = new byte[1024];
String deoutput = null;
BufferedReader in =null;
if (responseCode == con.HTTP_CREATED) { in =new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
System.out.println("Response received from Fusion string buffer :"+inputLine);
} in .close();
ResponseStr = response.toString();
System.out.println("response string :"+ResponseStr);
bresponse = ResponseStr.getBytes("UTF-8");
System.out.println("Response received from Fusion Bytes :"+bresponse);
deoutput = unzip(bresponse);
System.out.println("Decompressed response :"+deoutput);
} else { in =new BufferedReader(new InputStreamReader(con.getErrorStream()));
System.out.println("Response Content Type :"+con.getContentType());
System.out.println("Response Content Encoding :"+con.getContentEncoding());
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\r");
System.out.println("Response received from Fusion string buffer :"+inputLine);
}
in .close();
ResponseStr = response.toString();
System.out.println("response string :"+response);
bresponse = ResponseStr.getBytes();
for (int i=0; i < bresponse.length; i++)
{
System.out.println("byte code :"+i+" "+bresponse[i]);
}
System.out.println("Response received from Fusion Bytes :"+Charset.defaultCharset()+bresponse);
deoutput = unzip(bresponse);
FileOutputStream fos = new FileOutputStream("fileName1.gz");
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(ResponseStr);
outStream.close();
System.out.println("Decompressed response :"+deoutput);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static String unzip(byte[] compressed) {
if ((compressed == null) || (compressed.length == 0)) {
System.out.println("The response is empty");
throw new IllegalArgumentException("Cannot unzip null or empty bytes");
}
if (!isZipped(compressed)) {
System.out.println("The response is not zipped");
return new String(compressed);
}
StringBuilder output = new StringBuilder();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
System.out.println("After byte array input stream :");
try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
try (InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream, StandardCharsets.UTF_8)){
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
System.out.println("buffer reader :"+bufferedReader.readLine());
while ((line = bufferedReader.readLine()) != null) {
output.append(line);
System.out.println("line :"+output.toString());
}
} catch(IOException e) {
throw new RuntimeException("Failed to read bufferedReader content", e);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
return output.toString();
}
public static boolean isZipped(final byte[] compressed) {
System.out.println("(byte)(GZIPInputStream.GZIP_MAGIC) is "+(byte)(GZIPInputStream.GZIP_MAGIC));
System.out.println("gzip magic is "+(byte)(GZIPInputStream.GZIP_MAGIC >> 8));
return (compressed[0] == (byte)(GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte)(GZIPInputStream.GZIP_MAGIC >> 8));
}
}

Invoking Rest API using java client passing json object

I am new to JSON. I am invoking a public rest API
https://api.gdc.cancer.gov/cases
I want to query all the cases for a particular disease type( for example TCGA-LAML mentioned below).
in SOAP Ui when I POST below request in JSON format .It gives me perfect answer
{
"filters":
{"op":"in",
"content":{
"field":"cases.project.project_id",
"value":["TCGA-LAML"]
}
}
}
But I have to call POST through a java client. Even after Trying hard I am not able to set the input parameters correctly.
I am posting my code here. Can you please help me correcting the code.
package downloadtoolproject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Newtest {
public static String sendPostRequest(String requestUrl, String payload) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
{
jsonString.append(line);
System.out.println(line);
}
br.close();
connection.disconnect();
}
catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString() ;
}
public static void main(String [] args)
{
String payload = "{\"field\":\"project_id\",\"value\":[\"TCGA-LAML\"]}";
String requestUrl="https://api.gdc.cancer.gov/cases";
sendPostRequest(requestUrl, payload);
}
}
I think the following solution should work for you
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Newtest {
public static String sendPostRequest(String requestUrl, String payload) {
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
System.out.println(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
public static void main(String[] args) {
List<String> values = new ArrayList<>();
values.add("TCGA-LAML");
String requestUrl = "https://api.gdc.cancer.gov/cases";
sendPostRequest(requestUrl, preparePayload(values));
}
private static String preparePayload(List<String> values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append("\"" + value + "\",");
}
String desiredValue = sb.toString().substring(0, sb.toString().length() - 1);
return "{ \"filters\": {\"op\":\"in\", \"content\":{ \"field\":\"cases.project.project_id\", \"value\":[" + desiredValue + "] } } }";
}
}
You just need to add all the input values in the values List and pass it to the preparePayload method ,it will convert it into a valid payload.

facebook login using java

I am looking for a way to login to Facebook without a browser.
I want to obtain the access token without a browser.
Login is required in order to obtain the access token.
-Login Java examples
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpUrlConnectionExample {
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
String url = "https://www.facebook.com/login.php?login_attempt=1";
String facebook = "https://www.facebook.com/";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "sainstia#gmail.com", "1111");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);
// 3. success then go to facebook.
String result = http.GetPageContent(facebook);
try {
String content = result;
File file = new File(".\\facebook_page.html");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.facebook.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://www.facebook.com/login.php?login_attempt=1");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
public String getFormParams(String html, String username, String password) throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("login_form");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("email"))
value = username;
else if (key.equals("pass"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
GetPageContent (String url) {
.....
.....
  setCookies (. conn.getHeaderFields () get ("Set-Cookie"));
......
}
I could not have a "Set-Cookie" value.
I can not find the "Set-Cookie".
What should I do to solve this problem?
You should use Jsoup i just finished making a program that did exactly this it logged onto a website and then i could manipulate anything on the website as i needed as long as you match the GETrequests you can log on to the wesbsite like this.
Connection.Response response = Jsoup.connect(url).method(Connection.Method.GET).execute();
response = Jsoup.connect(url)
.cookies(response.cookies())
.data("Action", "Login")
.data("User", "My_UserName")
.data("Password", "My_Password")
.method(Connection.Method.POST)
.followRedirects(true)
.timeout(50000)
.execute();

Twitter call request

I have problem with my source code for twitter request. Response that is returned from twitter is blank String. Can you advice where can be problem?
I have registered my app normally on dev.twitter.com. It is called Reach Count.
This code is brought from this tutorial: http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/
package count_reach_twitter;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* #author Martin
*/
public class TwitterCall {
// Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
// Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
// Constructs the request for requesting a bearer token and returns that token as a string
private static String requestBearerToken(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys("My customer key","My customer secret key");
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Reach Count");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
//writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
System.out.println("Response: " + readResponse(connection));
System.out.println("End");
JSONObject obj = new JSONObject(readResponse(connection)); //(JSONObject)JSONValue.parse(readResponse(connection));
//obj.
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
return ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
// Fetches the first tweet from a given user's timeline
public static String fetchTimelineTweet(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Reach Count");
connection.setRequestProperty("Authorization", "Bearer " + requestBearerToken("https://api.twitter.com/oauth2/token"));
connection.setUseCaches(false);
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONArray obj = new JSONArray(readResponse(connection));//(JSONArray)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tweet = ((JSONObject)obj.get(0)).get("text").toString();
return (tweet != null) ? tweet : "";
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Main function is calling next method:
System.out.println(TwitterCall.fetchTimelineTweet("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Dj_Fedy&count=50"));
Thank you
I'm not sure why your code gets a 403 from Twitter. I can think of two things:
According to the bottom of Application-only authentication doc, a 403 response is given when you use a bearer token on endpoint which doesn't support application-only auth. I cannot find whether a GET on statuses/user_timeline is allowed with application-only auth.
According to the GET statuses/user_timeline doc, you can only request tweets for a protected user when the authenticated user either "owns" the timeline or is an approved follower of the owner. I'm not sure whether this is the case for you.

Categories