Consume jira rest with java - json

i'm using java and i want to consume the json in this url : http://jiraserver/rest/dev-status/latest/issue/detail?issueId=13879&applicationType=stash&dataType=repository
on the browser this url works perfectly and i get all json data needed but in my java program i get
java.io.IOException: Server returned HTTP response code: 400 for URL:
http://jiraserver/rest/dev-status/latest/issue/detail?issueId=13879&applicationType=stash&dataType=repository
public static void main(String[] args) {
System.out
.println(jsonGetRequest("http://jiraserver/rest/dev-status/latest/issue/detail?issueId=13879&applicationType=stash&dataType=repository
"));
}
private static String streamToString(InputStream inputStream) {
String text = new Scanner(inputStream, "UTF-8").useDelimiter("\\Z").next();
return text;
}
public static String jsonGetRequest(String urlQueryString) {
String json = null;
try {
URL url = new URL(urlQueryString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
InputStream inStream = connection.getInputStream();
json = streamToString(inStream); // input stream to string
} catch (IOException ex) {
ex.printStackTrace();
}
return json;
}
am i missing something ? if there's any simple implementation to consume that url feel free

Related

How to send data from libgdx project to web?

I would like to work on moving the json data from libgdx to my web server, but I am not sure how to do it. The method below was created by referring to libgdx's documentation.
private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
#Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
#Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}
It is possible to receive data transmitted from a web server.
But, this method can't send data to web server.
Can you tell me how to move data from libgdx project to web server?
This is the data transmitted to the web server:
final String requestJson = json.toJson(requestObject);
We are using the following Code (as you have more control over the request as opposed to using gdx.net), works like a charm, just don't execute on the main thread - body is your JSON as String
URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);
Method stringFromStream:
public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}

How do I send a HTTP request using OAUTH2 in Android?

I am trying to retrieve the data from my account by connecting to the Fitbit API. I have my app returning the Access Token I need to make the HTTP Request that returns the JSON but anything that I try, it returns an error. I have two Activities - MainActivity.java and TestActivity.java
In MainActivity.java I am simply opening a Chrome Custom Tab to direct the user to the Fitbit Authentication(Login) page. Once the user enters their details they are redirected back to the TestActivity.java as per the Fitbit API documentation. I am then printing the Acess Token which proves to me that it is connecting to the API.
What I need to do it make an HTTP request to returns the sleep data in JSON format. I know how to do it in Java but I am unsure how to do it in Android using the AsyncTask way. Any help is appreciated!
public class TestActivity extends AppCompatActivity {
String string;
String token;
#Override
protected void onNewIntent(Intent intent) {
string = intent.getDataString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
onNewIntent(getIntent());
//Toast.makeText(TestActivity.this, string , Toast.LENGTH_LONG).show();
Log.e("TAG", string);
Log.e("TAG", string.substring(string.indexOf("&access_token")+14));
token = string.substring(string.indexOf("&access_token")+14);
Context context = getApplicationContext();
Toast toast = Toast.makeText(context,"Access Token: "+ token,Toast.LENGTH_LONG );
Log.i("TAG", "Access Token: "+ token);
new JSONTask().execute("https://api.fitbit.com/1.2/user/-/sleep/date/2018-01-30.json");
}
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try
{
URL url = new URL(params[0]);
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) !=null)
{
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
Log.i("TAG", s);
}
}
I ended up having a breakthrough with this question. I figured out that I was extracting the Access Token incorrectly. So, instead of doing the following:
token = string.substring(string.indexOf("&access_token")+14);
I instead had to use this:
token = string.substring(string.indexOf("&access_token")+36,308);
The App was then able to make the necessary HTTP request to the Fitbit API which returned the JSON data that I needed.
One order of codes should be changed for preventing FC.
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);

Sisense - REST API - republish Not Working + 500 Internal Server Error

Using JAVA, I am trying to republish a dashboard to a particular User. It returns me HTTP status 500. Below is the code for it.
String sisenseURL = surl; // This is correct URL to POST API for PUBLISH
String urlParameters = "force=true";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
URL url = new URL( sisenseURL );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setRequestProperty("Authorization", accessToken);
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write( postData );
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
stringBuffer.append(line);
}
in.close();
The request runs file with POSTMAN as well as with the Swagger UI for Sisense.
Any help would be greatly appreciated.
TIA
Ashutosh
Here is a java example for sisense V6.7 of updating dashboard shares using the rest API
You didnt share your payload so not sure if thats the problem, but the example below worked for me.
I took the sendPostRequest code from here
import java.io.*;
import java.net.*;
public class Runner {
public static void main(String[] args){
try {
//Dashboard shares payload
String payload = "{\"sharesTo\":[{\"shareId\":\"58504c5221785b627cb4361d\",\"type\":\"user\",\"subscribe\":false},{\"shareId\":\"58505ba6ec4df9701a000019\",\"type\":\"user\",\"rule\":\"view\",\"subscribe\":false}]}";
String str = sendPostRequest(getDashboardUrl(), payload);
System.out.println("Done");
}
catch (RuntimeException e){
}
}
public static String sendPostRequest(String requestUrl, String payload) {
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; charset=UTF-8");
connection.setRequestProperty("Authorization", getAuthorization());
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public static String getDashboardUrl(){
//Sisense domain
String baseURL = "http://localhost:8081";
return baseURL + "/api/shares/dashboard/5850511cec4df9701a000013";
}
public static String getAuthorization(){
return "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiNTg1MDRjNTIyMTc4NWI2MjdjYjQzNjFkIiwiYXBpU2VjcmV0IjoiOGUwZDIyOWItY2VmMS0xYTE4LTNhYWEtYmY1ZmE1ZmNkNTExIiwiaWF0IjoxNTE1MDEzMzkxfQ.zgx0Nv8YztfM2rm5WTCnJ0R6C_n5V-HNkEZgAcINfs4";
}
}

HTTP error 500 on Android

So here is my code, its purpose is to fecth a json file. I get an error 500 from the server, which means I know that it is an internal server error. As I can't access to the logs of the the server, I'm pretty much stuck from now... I read about session and cookies, maybe that's it. What do you guy think of it ?
private class ListingFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "ListingFetcher";
public static final String SERVER_URL = "http://www.myurl.com/listing.json";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Listing> events = new ArrayList<Listing>();
events = Arrays.asList(gson.fromJson(reader, Listing[].class));
content.close();
handlePostsList(events);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
My code is perfectly working. THe only mistake is on this line :
HttpPost post = new HttpPost(SERVER_URL);
Which should be
HttpGet get = new HttpGet(SERVER_URL);

how to handle http 400 and 401 error while using webclient to download JSON

I am using an api that returns an error 400 if URL is invalid and error 401 if daily qouta is exhausted by 50%. it also returns the json but am not able to download this json as an exception occurs if these error occurs. the api am using is
http://www.sharedcount.com/documentation.php
the code am using write now is...
private void _download_serialized_json_data(Uri Url)
{
var webClient = new WebClient();
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(Url);
}
catch (Exception) { }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
try
{
Json = e.Result;
}
catch (Exception ex)
{
}
if(Json!=null)
{
data=JsonConvert.DeserializeObject<RootObject>(Json);
result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne;
}
else
{
result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%.";
}
}
currently am showing both errors if exception occurs. but i want to download the json and display that. how should i do that
To get the response content, you will need to use System.Net.Http.HttpClient instead. Install it from here: Microsoft HTTP Client Libraries
Then try this:
private async void Foo2()
{
Uri uri = new Uri("http://localhost/fooooo");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
HttpStatusCode statusCode = response.StatusCode; // E.g.: 404
string reason = response.ReasonPhrase; // E.g.: Not Found
string jsonString = await response.Content.ReadAsStringAsync(); // The response content.
}
You can try something like this,
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
if(e.Error != null)
{
//Some error occured, show the error message
var ErrorMsg = e.Error.Message;
}
else
{
//Got some response .. rest of your code
Json = e.Result;
}
}
I ran into this same issue using WebClient, I saw the error response stream being captured in Fiddler, but my .NET code was catching the exception and did not appear to be capturing the response stream.
You can read the Response stream from the WebException object to get the response data stream out.
using (System.Net.WebClient client = new System.Net.WebClient())
{
string response = "";
try
{
response = client.UploadString(someURL, "user=billy&pass=12345");
}
catch(WebException ex)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
string exResponse = sr.ReadToEnd();
Console.WriteLine(exResponse);
}
}
}