Here is my code:
public String readTheUrl(String place) throws IOException {
String data = "";
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(place);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.connect();
int response=httpURLConnection.getResponseCode();
inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = (bufferedReader.readLine())) != null) {
stringBuffer.append(line);
}
data = stringBuffer.toString();
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
inputStream.close();
httpURLConnection.disconnect();
return data;
}
When I am using this code for loading other url, it is working perfectly, but in case of
"https://api-crt.cert.havail.sabre.com/v1/shop/flights?origin=FRA&destination=DFW&departuredate=2019-10-28&returndate=2019-11-10&pointofsalecountry=DE"
it always return null. I tested this api with postman, and I loaded JSON file. Is there any problem with url or it needs some specific loading? Thank you!
Related
In debugging i can see that it puts everything what i need into the sb StringBuilders, but after the second sb the data just disapears and what was prevously written into the safety_string gets deleted aswell, don't know why.
Here is the whole code, changed it a little since i posted.
Still the same, it's not an out of scope, because the result of getting_kat i do receive, only the result of getting_ter is missing.
#Override
public String doInBackground(String... voids) {
String result="";
result=getting_kat();
result+=getting_ter();
//Making sure it gets put into the safety string
safety_string=result;
return result;
}
public String getting_kat(){
String result="";
String resultkat = null;
String connstr = "My connection string";
try {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
InputStream ips = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
//Line by Line reading the data from php
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
//String it together into one line
resultkat = sb.toString();
//Adding a separator for later split
result=resultkat+"#KATEGORIA/TERMEK#";
br.close();
ips.close();
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
public String getting_ter(){
String result="";
String resultter=null;
String connstr2 = "My connection string 2";
try {
URL url = new URL(connstr2);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
InputStream ips = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
//Line by Line reading the data from php
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
//String it together into one line
resultter = sb.toString();
result=resultter;
br.close();
ips.close();
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
I can't see bug in the code. I cleaned it up a bit for you but it should work both before and after my changes. You don't describe what is actually going wrong with it. In debugging you may just be getting timeout on your connection.
public String doInBackground(String... voids) {
String result = getting_kat() + "#KATEGORIA/TERMEK#" + getting_ter();
//Making sure it gets put into the safety string
safety_string = result;
return result;
}
public String getting_kat() {
String result = "";
String connstr = "My connection string";
try {
HttpURLConnection http = connect(connstr);
result = readFromPhp(http);
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
public String getting_ter() {
String result = "";
String connstr = "My connection string 2";
try {
HttpURLConnection http = connect(connstr);
result = readFromPhp(http);
http.disconnect();
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
private HttpURLConnection connect(String connstr) throws IOException {
URL url = new URL(connstr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
return http;
}
private String readFromPhp(HttpURLConnection http) throws IOException {
// try-with-resources - so you don't have to call close()
try (
InputStream ips = http.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 8)
) {
StringBuilder sb = new StringBuilder();
String line;
//Line by Line reading the data from php
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
//String it together into one line
return sb.toString();
}
}
I'm using Asynctask For network call in android Studio.I have php web API's I dont know why but Some of them Not Working in android .
Following is My AsyncTask Class...
private class AsyncAddfriend extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://ishook.com/users/friends/send_friend_request_json/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
}
I'm using same Code for other API's also they all are working fine but this api is not working.
I have Tested This API in post man its working but in not working android .
Hope You will understand My problem....
I am trying to get response data of a Http request. My code looks like this :
public class Networking {
// private variables
private URL mUrl;
private InputStream mInputStream;
public void Networking() {}
public InputStream setupConnection(String urlString) {
// public variables
int connectionTimeout = 10000; // milliseconds
int readTimeout = 15000; // milliseconds
try {
mUrl = new URL(urlString);
try {
// initialize connection
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
// setup connection
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(readTimeout);
connection.setRequestMethod("GET");
connection.setDoInput(true);
// start the query
try {
connection.connect();
int response = connection.getResponseCode();
if (response == 200) {
// OK
mInputStream = connection.getInputStream();
return mInputStream;
} else if (response == 401) {
// Unauthorized
Log.e("Networking.setupConn...", "unauthorized HttpURL connection");
} else {
// no response code
Log.e("Networking.setupConn...", "could not discern response code");
}
} catch (java.io.IOException e) {
Log.e("Networking.setupConn...", "error connecting");
}
} catch (java.io.IOException e) {
Log.e("Networking.setupConn...", "unable to open HTTP Connection");
}
} catch (java.net.MalformedURLException e) {
Log.e("Networking.setupConn..", "malformed url " + urlString);
}
// if could not get InputStream
return null;
}
public String getStringFromInputStream() {
BufferedReader br = null;
StringBuilder sb = new StringBuilder(5000);
String line;
try {
br = new BufferedReader(new InputStreamReader(mInputStream), 512);
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (java.io.IOException e) {
Log.e("BufferReader(new ..)", e.toString());
return null;
} finally {
if(br != null) {
try {
br.close();
}catch (java.io.IOException e) {
Log.e("br.close", e.toString());
}
}
}
return sb.toString();
}
}
The problem is that the getStringFromInputStream function always returns a string that is 4063 bytes long. ALWAYS! No matter what the url.
I checked, and the (line = br.readLine()) part of the code always returns a string of fixed length of 4063.
I don't understand this. Please help.
This my code which works for me:
public String getDataFromUrl(String httpUrlString)
URL url = new URL(httpUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode != HttpStatus.SC_OK) {
return null;
} else { // success
BufferedReader in = null;
StringBuffer str = new StringBuffer();
try {
in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
str.append(inputLine);
}
} finally {
if (null != in) {
in.close();
}
urlConnection.disconnect();
}
return str.toString();
}
}
In my opinion, it could be helpful for you if you use a library for http request.
I could suggest retrofit or volley.
Besides that, you could just try other methods to get the String from the InputStream, there is an interesting reply for that here
The one that I've used is
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
return buf.toString();
I'm trying to make a GET AJAX request on some site using java.
My code is the following:
String cookie = getRandomString(16); //Getting a random 32-symbol string
String url = "https://e-kassa.org/core/ajax/stations_search.php?"
+ "q=%D0%BE&limit=10×tamp=1352028872503";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
InputStream is = conn.getInputStream();
int buffer;
while((buffer = is.read()) != -1)
System.out.print(buffer);
is.close();
conn.disconnect();
But the problem is that there's nothing to download from the InputStream is. But if I use my browser to do the same thing, I'll get a response, composed of text lines of the following format:
CITY_NAME|SOME_DIGITS
So, can anybody tell me, how can I make such a request in an appropriate manner?
UPD: without cookies I have the same behaviour (in the browser everything's fine, but not in Java).
Can you please try with:
BufferedReader rd = null;
try {
URL url = new URL("https://e-kassa.org/core/ajax/stations_search.php?"
+ "q=%D0%BE&limit=10×tamp=1352028872503");
URLConnection conn = url.openConnection();
String cookie = (new RandomString(32)).nextString();
conn.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
// Get the response
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rd != null) {
try {
rd.close();
} catch (IOException e) {
}
}
}
This is peace of code that works properly in my projects. :)
Try the following thing.
HttpURLConnection connection = null;
try {
String url = "https://e-kassa.org/core/ajax/stations_search.php?"
+ "q=%D0%BE&limit=10×tamp=1352028872503";
URL url = new URL(url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
connection.connect();
connection.getInputStream();
int buffer;
while((buffer = is.read()) != -1)
System.out.print(buffer);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if(null != connection) { connection.disconnect(); }
}
When i send a POST Request to a Server, if the response is 200 i get the JSON body. However for unsuccessful requests the servers send a 400 response code but my android code throws a FileNotFoundException. Is there any difference between reading a 400 response and a 200 response ?
StringBuffer responseBuilder = new StringBuffer();
String line = null;
HttpURLConnection conn = null;
OutputStream out = null;
BufferedReader rd = null;
System.setProperty("http.keepAlive", "false");
try
{
conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(NetworkConstants.CONNECTION_TIMEOUT);
conn.setReadTimeout(NetworkConstants.SOCKET_TIMEOUT);
out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
String s = formatParams();
Log.d("-------------------------------------------------->", s);
writer.write(s);
writer.flush();
writer.close();
}
catch (Exception e)
{
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
try
{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
responseBuilder.append(line);
if (!rd.ready())
{
break;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
conn.disconnect();
}
}
String response = responseBuilder.toString();
Log.d("###########################", response);
return response;
Kind Regards,
Use getErrorStream() for this. From the docs:
If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields().
Sample code:
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode >= 400 && responseCode <= 499) {
Log.e(TAG, "HTTPx Response: " + responseCode + " - " + httpURLConnection.getResponseMessage());
in = new BufferedInputStream(httpURLConnection.getErrorStream());
}
else {
in = new BufferedInputStream(httpURLConnection.getInputStream());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
urlResponse.append(line);
}
If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream() to parse the json and show the message provided by your backend.
I know it's been a long time since the question was asked but for the benefit of other people who are still having this kind of problem please note that another possible cause of the problem is using "connection.getContent()" to get InputStream. like so:
InputStream is = (InputStream) connection.getContent();
this can create a problematic situation where response code larger than 399 will not be processed at all.
so the recommendation is to work directly with getInputStream() and getErrorStream() as shown in previous comments and as in the following example:
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
String urlString = "http://www.someurl.com";
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream is;
int responseCode = connection.getResponseCode();
if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
StringBuilder response = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String tempLine;
while ((tempLine = bufferedReader.readLine()) != null) {
response.append(tempLine);
}
String serverResponse = response.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}