I'm writing an Android app. Now I try to get JSON from an URL with this method:
public String getInfo(String adress) throws Exception {
URL url = new URL(adress);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
int status = uc.getResponseCode();
InputStream in = uc.getInputStream();
InputStreamReader inRead = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inRead);
String line;
String result = "";
while ((line = br.readLine()) != null) {
result += line;
}
return result;
}
On this url: http://www.rtvlansingerland.nl/tag/nieuws/?json=get_posts this method is perfectly working while on this url: http://www.rtvlansingerland.nl/?json=get_post&id=24411 the status variable goes to 400 which gives a url not found exception and uc.getInputStream() returns a filenotfound error.
If I open the URL in my browser it returns perfectly valid JSON (checked with jsonlint).
Does anyone have an option what could be wrong?
Thx in advance.
First of all you should not use network connection on main thread and after that you should check whether the file exist or not on URL if exist then proceed
Related
I'm trying to send a Telegram message from an Android app. I want that message to contain a hyperlink so I used parse_mode=html param but I have a problem with the anchor tag. It seems that java is treating my URL as a local path.
This is the code:
String location = "http://www.google.com";
urlString = String.format("https://api.telegram.org/bot<bot_token>/sendMessage?chat_id=<chat_id>&parse_mode=html&text=<a href=%s>Location</a>", location);
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
StringBuilder sb = new StringBuilder();
InputStream is = new BufferedInputStream(conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
And this is the error:
java.io.FileNotFoundException:
https://api.telegram.org/bot<bot_token>/sendMessage?chat_id=<chat_id>&parse_mode=html&text=<a href=http://google.com>Location</a>
How should I write this message so the href link will be treated as an external URL?
The error java.io.FileNotFoundException doesn't mean that it is treated as a local path.
It is HTTP 404 File Not Found. And it is the response from the server for your HTTP Request.
It seems that at first to provide proper <bot_token> and <chat_id> is needed. And second, you should urlencode that String before instantiating a URL object with it.
String encodedUrlString = URLEncoder.encode(urlString, "UTF-8");
URL url = new URL(encodedUrlString);
I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
I have a data access object which calls a web service. In my browser I can hit the web service using a url and it is successful.
http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json
But when try to execute the code below in my data access object I get a 405 error saying method not allowed.
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Accept", "application/json");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
int responseCode = httpCon.getResponseCode();
String responseMessage = httpCon.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
String jsonResponse = sb.toString();
out.close();
httpCon.disconnect();
Can someone help me with what might be wrong here?
Also maybe there is a better way to execute a web service to an external application and read the response using struts? Or do people think this method is okay?
thanks
If u are using GET method. Try the below code.
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
serviceRequest.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = serviceRequest.DownloadString(new Uri(url));
Thanks for your ideas however non of them were quite right. I fixed the 405 using the code below...
String requestURI = "http://myserver:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
By calling httpCon.getOutputStream()); you're not sending a HTTP GET anymore, but a HTTP POST.
Note: This is under the assumption you end up getting the implementation provided by Sun. Which will change GET to POST for backwards compatibility.
I'm trying to use twitter api in the following way:
String urlAdd = "https://api.twitter.com/1/following/ids.json?user_id=1000123";
URL url = new URL(urlAdd);
URLConnection urlConnection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
getInputStream input stream throws IOException, it happens because i've reached my request limit.
I want to be able to distinghuish between request limit error and other errors. Twitter returns error message in json format, but i can't read it because of the thrown exception.
Any ideas on how can I fetch the error message?
I found a way to do it:
String urlAdd = "https://api.twitter.com/1/following/ids.json?user_id=1000123";
URL url = new URL(urlAdd);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
I am trying to get an InputStream from a URL. The URL can be a opened from Firefox. It returns a json and I have installed an addon for viewing json in Firefox so I can view it there.
So I tried to get it from Java by:
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
But it is throwing an IOException in urlConnection.getInputStream().
I also tried:
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = url.openStream();
But no luck.
Any information is appreciable. Thanks in advance.
Thank you everybody. This is a weird problem but at last I solved it.
The URL I am requesting is
http://api.themoviedb.org/2.1/Movie.search/en/json/api_key/a nightmare on elm street
Now browser replaces the spaces between "a nightmare on elm street" by "%20" internally and parses. That is why the requested server can response by that request. But From Java I didn't replaced that spaces by "%20", so it turns into Bad Request, source.
Now it is working.
BufferedReader reader = new BufferedReader(new InputStreamReader(((HttpURLConnection) (new URL(urlString)).openConnection()).getInputStream(), Charset.forName("UTF-8")));
I had a similar issue and my url was:
http://www.itmat.upenn.edu/assets/user-content/documents/ITMAT17. October 10 2017_.pdf
which obviously contained spaces.
These caused java.io.IOException Server returned HTTP response code: 400 in the following code:
java.net.URL url = new URL(urlString);
java.io.InputStream in = url.openStream();
If you copy the above url and paste in browser, you will realize that browser adds '%20' for the spaces. So I did it manually with the following code and the problem is solved.
if(urlString.contains(" "))
urlString = urlString.replace(" ", "%20");
Complete code/answer should be:
if(urlString.contains(" "))
urlString = urlString.replace(" ", "%20");
java.net.URL url = new URL(urlString);
java.io.InputStream in = url.openStream();
are you setting up the connection correctly? here's some code that illustrates how to do this. Note that I am being lazy about exception handling here, this is not production quality code.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLFetcher {
public static void main(String[] args) throws Exception {
URL myURL = new URL("http://www.paulsanwald.com/");
HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder results = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
results.append(line);
}
connection.disconnect();
System.out.println(results.toString());
}
}
encode the parameters in the URL as follows:
String messageText = URLEncoder.encode(messageText, "UTF-8");
I a encountered same error. In my case, it was because the sizjwt token in the header was larger than acceptable size by mule soft proxy. One option is to increase the size of acceptable header size in mule soft, or reduce the size of token by removing some of the permissions assigned to the user id