Getting the error code message in twitter api request (java) - java

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));

Related

Android HttpsURLConnection: getErrorStream works but not getInputStream

I want to get a json string from my remote server.
I have a very weird problem as I manage to get my json string only thanks to getErrorStream but not thanks to getInputStream.
Here is my code:
URL url = new URL("my_https_url");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseStatusCode = connection.getResponseCode(); // ERROR 500 HERE
InputStream inputStream;
if(responseStatusCode != HttpsURLConnection.HTTP_OK ) {
inputStream = connection.getErrorStream(); // I pass through here
} else {
inputStream = connection.getInputStream();
}
response = IoUtils.readAll(inputStream); // I get my json string properly after being passed through getErrorStream()
If I remove my 'if statement' and try to do only:
inputStream = connection.getInputStream()
I get a fileNotFoundException.
Anybody has a clue how to solve this issue?
Thanks.

Java - Reading POST from HttpURLConnection throwing response code 400

I am opening an HttpURLConnection and with POST method, I am sending a JSON request that I build form another class. The JSON is structured correctly since I have validated it on debugging. The exception is thrown when trying to read the output response given from the server. This is the Error given
java.io.IOException: Server returned HTTP response code: 400 for URL:
However when I manually try to enter the Url from a web browser with a POST method chrome extension. I can view the response and everything works. So I am sure it has something to do with the following code where I make the connection and read/write.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//add request header
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//mapping objects to json
BatchRequest requestParameters = new BatchRequest(o,d);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestParameters);
connection.setDoOutput(true);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
// this is where the program throws the exception
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Both the URL and the JSON request are correct since They work when I try a manual conenction over a browser.
A DataOutputStream is not needed. Just:
OutputStream os = con.getOutputStream();

405 - method not allowed calling web service from struts

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.

Java inputstream giving io.filenotfound exception while working on other URL

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

How to get the Response Back from the Remote Server using an HttpURLConnection Object?

I am trying to send an HTTP POST Request to a remote server using an instance of the HttpURLConnection class. Although, I am able to get a response code and a response message, when I try to write the input stream into a StringBuffer, I am not able to actually read any lines.
When I analyzed the packets sent from WireShark, I noticed that a full response was being sent from the remote server. My only guess as to why I am not able to see it in the Java program is because the time in which I try to read from the InputStream is too late.
So, how do I read the immediate, full response from the remote server using my HttpURLConnection object? Below is the code that I am using:
HttpURLConnection conn = null;
String urlStr = "...";
URL url = null;
try
{
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
...
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
...
}...
Okay, never mind. It turns out that what I was looking for was in the HTTP Respone's header. So, I got what I needed by looking through its headers. ::Face Palm::

Categories

Resources