Getting a null return from BufferedReader - java

So I'm trying to upload an image to Imgur using their v3 API (http://api.imgur.com/) and when I get the response it returns me with
null : null
Here is my full code.
import java.util.List;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
//import org.omg.DynamicAny.NameValuePair;
import org.apache.http.NameValuePair;
public class Upload {
public static void main (String[] args) {
System.out.println(Imgur("C:\\Users\\wiesa\\Desktop\\image.jpg", "2313fab45c25337"));
}
public static 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();
}
}
}
Depending what I initilize the string "all" to if I make it a
null
Then the return is
null : null
BUt if I initialize it to
""
Then the return is
: null
I Changed the line to
String all = null;
//loop through response
String line = null;
while ((line = rd.readLine()) != null) {
all = all + " : " + line;
}
return all;
and the I get the return
null : {"data":{"error":"Malformed auth header","request":"/3/image","parameters":"image = iVBORw0KGgoAAAANSUhEUgAAB4AAAASwCAIAAACVUsChAACAAElEQVR42uzdCXebyrI2YEuyY8fzPCbZOyfZd597v///...","method":"POST"},"success":false,"status":403}

At each iteration, you're reading two lines instead of one. Change
while (rd.readLine() != null) { // first line read
all = all + " : " + rd.readLine(); // second line read
}
to
String line;
while ((line = rd.readLine()) != null) {
all = all + " : " + line;
}

Related

Error: "The Method is undefined for the type object" android project eclipse

I'm new android development and I have been researching this for some time however I can't seem to correct the error. I have a "The Method is undefined for the type object" error on both getStatusCode() and getReasonPhrase(). Any help would be appreciated.
My code as fallows
package com.javapapers.java.io;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class HttpUtil {
public String getHttpResponse(HttpRequestBase request) {
String result = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String reason = httpResponse.getStatusLine().getReasonPhrase();
StringBuilder sb = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
result = sb.toString();
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return result;
}
}

getApplicationContext() Issue

I'm following this tutorial :
http://www.tutos-android.com/importer-ajouter-certificat-ssl-auto-signe-bouncy-castle-android/comment-page-2#comment-2159
(SSl auto signed certificate problem)
JsonParserFUnction code :
package com.example.androidsupervision;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class JsonReaderPost {
public JsonReaderPost() {
}
public void Reader() throws IOException, JSONException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
String ints = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query","SELECT+AlertId+FROM+Orion.Alerts"));
//HttpClient client = new DefaultHttpClient();
**//Here is the problem**
HttpClient client =new MyHttpClient(getApplicationContext());
HttpPost httpPost = new
HttpPost("https://192.168.56.101:17778/SolarWinds/InformationService/v3/Json/Query");
httpPost.addHeader("content-type", "application/json");
httpPost.addHeader("Authorization", "Basic YWRtaW46");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response;
String result = null;
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
// System.out.println("RESPONSE: " + result);
Log.e("Result", "RESPONSE: " + result);
instream.close();
}
// Converting the String result into JSONObject jsonObj and then into
// JSONArray to get data
JSONObject jsonObj = new JSONObject(result);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject r = results.getJSONObject(i);
ints = r.getString("AlertId");
Log.e("Final Result", "RESPONSE: " + ints);
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I get in this line an error :
HttpClient client =new MyHttpClient(getApplicationContext());
The error is : The method getApplicationContext() is undefined for the type JsonReaderPost
You should send the context of your activity when you instantiate the class:
private Context mContext;
public JsonReaderPost(Context mContext) {
this.mContext = mContext;
}
Then, you should use "mContext" instead of getApplicationContext();
It is unknown because your class doesn't extend any other Class that has a Context, so it doesn't know what that method is. Such is, for example, an Activity.
However, using getApplicationContext(), unless you really know what you're doing, is almost always wrong. This will bring undesired behaviors like Exceptions when handled not properly. You should always use the Context of the class you're handling.
You can know which classes implement Context and get more info on contexts here.

youtube to mp3 conversion using web site

I'm trying to make program that can download youtube videos as mp3 files. I used this site youtube-mp3.org in order to achive that. So, i downloaded content of www.youtube-mp3.org/?c#v=sTbd2e2EyTk where sTbd2e2EyTk is video id, now i have to get link to mp3 file(in this case http://www.youtube-mp3.org/get?video_id.....) but there is no link in downloaded content. I noticed that chrome developers tools(ctrl+shift+j, tab Elements) show that link and view source(ctrl+u) option in chrome gives me the same result which i get by downloading page using java. How can i get that link?
I tried to fetch data using JSoap but those data that i need are not loaded on page immediately so i cannot get them.
Next code is for downloading content of web page...
URL tU = new URL("http://www.youtube-mp3.org/?c#v=sTbd2e2EyTk");
HttpURLConnection conn = (HttpURLConnection) tU.openConnection();
InputStream ins = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(ins));
String line;
StringBuffer content = new StringBuffer();
while ((line = rd.readLine()) != null) {
content.append(line);
}
System.out.println(content.toString());
I used this method for getting file but i need link..
private static void downloadStreamData(String url, String fileName) throws Exception {
URL tU = new URL(url);
HttpURLConnection conn = (HttpURLConnection) tU.openConnection();
String type = conn.getContentType();
InputStream ins = conn.getInputStream();
FileOutputStream fout = new FileOutputStream(new File(fileName));
byte[] outputByte = new byte[4096];
int bytesRead;
int length = conn.getContentLength();
int read = 0;
while ((bytesRead = ins.read(outputByte, 0, 4096)) != -1) {
read += bytesRead;
System.out.println(read + " out of " + length);
fout.write(outputByte, 0, bytesRead);
}
fout.flush();
fout.close();
}
Found this
package main.java.com.thezujev.theyoutubepld.logic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* #author azujev
*
*/
public class YouTubeMP3 {
public static String[] getLink(String url) throws ClientProtocolException, IOException {
boolean passCode = false;
String h = "";
String title = "";
String result = "";
String[] returnVal = {"",""};
Map<String, String> jsonTable;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpInitialGet = new HttpGet("http://www.youtube-mp3.org/api/pushItem/?item=http%3A//www.youtube.com/watch%3Fv%3D" + url + "&xy=_");
httpInitialGet.addHeader("Accept-Location", "*");
httpInitialGet.addHeader("Referrer", "http://www.youtube-mp3.org");
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1");
httpInitialGet.setParams(params);
HttpResponse firstResponse = httpClient.execute(httpInitialGet);
try {
if (firstResponse.getStatusLine().toString().contains("200")) {
passCode = true;
}
} finally {
httpInitialGet.releaseConnection();
}
if (passCode) {
while (true) {
HttpGet httpStatusGet = new HttpGet("http://www.youtube-mp3.org/api/itemInfo/?video_id=" + url + "&adloc=");
httpStatusGet.addHeader("Accept-Location", "*");
httpStatusGet.addHeader("Referrer", "http://www.youtube-mp3.org");
httpStatusGet.setParams(params);
HttpResponse secondResponse = httpClient.execute(httpStatusGet);
HttpEntity secondEntity = secondResponse.getEntity();
InputStream is = secondEntity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
httpStatusGet.releaseConnection();
result = result.replaceAll("\\}.*", "}");
result = result.replaceAll(".*?\\{", "{");
try {
JSONObject jsonData = new JSONObject(result);
JSONArray jsonArray = jsonData.names();
JSONArray valArray = jsonData.toJSONArray(jsonArray);
jsonTable = new HashMap<String, String>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
jsonTable.put(jsonArray.get(i).toString(), valArray.get(i).toString());
}
if (jsonTable.get("status").equals("serving")) {
h = jsonTable.get("h");
title = jsonTable.get("title");
break;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
returnVal[0] = "http://www.youtube-mp3.org/get?video_id=" + url + "&h=" + h;
returnVal[1] = title;
return returnVal;
} else {
//TODO: Error, vid not downloadable
}
return null;
}
}
An answer on a similar question:
Regarding the Terms of Service of the YouTube API
https://developers.google.com/youtube/terms/developer-policies
YOU CAN'T :
separate, isolate, or modify the audio or video components of any
YouTube audiovisual content made available through the YouTube API;
promote separately the audio or video components of any YouTube
audiovisual content made available through the YouTube API;
(Source: https://stackoverflow.com/a/26552805/5645656)
My answer:
It is possible using a different service. You can, for example, install YouTube-DL and use the Process API to interface the program.

parsing data error when search there is no search result

I've made a part of a code that makes a query on a remote server. but I have a problem when I'm Parsing data when there are no results of the query, does anyone nows how to handle this?
the code of the constructor that parse the data into an JSONArray is:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JsonParser {
static InputStream is = null;
static JSONObject json_data = null;
static String result = "";
// constructor
public JsonParser() {
}
public JSONArray getJSONFromUrl(ArrayList<NameValuePair> nameValuePairs, String url) {
//http post this will keep the same way as it was (it's important to do not forget to add Internet access to androidmanifest.xml
InputStream is = null;
String result ="";
JSONArray jArray = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response that we receive from the php file into a String()
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// try parse the string to a Json object
try {
//json_data = new JSONObject(result);
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return Json String
return jArray;
}
}
on url, namevaluepair if someone want to try I used this:
String url = "http://trialsols.webege.com/mobil.php";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("precio",data));
that is a example MySQL with PHP database, where data is an int for the field "precio" in English cost"
solution: before parsing data of the jArray, that is returned from this constructor I added an if(jArray!= null) so I can create a message in case of no results instead of parsing data

HTTPclient POST with problematic web site

I'm trying to retrive some data from a web site.
I wrote a java class which seems to work pretty fine with many sites but it doesn't work with this particular site, which use extensive javascript in the input fomr.
As you can see from the code I specified the input fields taking the name from the HTML source, but maybe this website doesn't accept POST request of this kind?
How can I simulate an user-interaction to retrieve the generated HTML?
package com.transport.urlRetriver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class UrlRetriver {
String stationPoller (String url, ArrayList<NameValuePair> params) {
HttpPost postRequest;
HttpResponse response;
HttpEntity entity;
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
postRequest = new HttpPost(url);
postRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(params));
response = httpClient.execute(postRequest);
entity = response.getEntity();
if(entity != null){
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (Exception e) {
result = "We had a problem";
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
void ATMtravelPoller () {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
String url = "http://www.atm-mi.it/it/Pagine/default.aspx";
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_s", "Viale romagna 1"));
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_e", "Viale Toscana 20"));
params.add(new BasicNameValuePair("sf_method", "POST"));
String result = stationPoller(url, params);
saveToFile(result, "/home/rachele/Documents/atm/out4.html");
}
static void saveToFile(String toFile, String pos){
try{
// Create file
FileWriter fstream = new FileWriter(pos);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
At my point of view, there could be javascript generated field with dynamic value for preventing automated code to crawl the site. Send concrete site you want to download.

Categories

Resources