AJAX GET requests in Java - java

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&timestamp=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&timestamp=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&timestamp=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(); }
}

Related

HttpURLConnection.getInputStream returns null

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!

Getting Empty response From PHP web API in android

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....

how can i obtain the response off server and if this contains "open" i can call other method, "contains" always marks error

/Method that sends the GPS pulse every time, when receiving the answer of the server if it contains "open" I have to stop sending pulse The method of eliminating the pulse I already have, I just have to know if the server response contains "open" because the response from the Server is too large string coming from a JSON/
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
final String routeId = ControlClass.pref.getString("routeId", "inaccesible");
int routeId2= Integer.parseInt(routeId);
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("route_id", routeId2);
jsonParam.put("timestamp", timestamp);
jsonParam.put("lat", 19.5216103);
jsonParam.put("lon", -99.21071050509521);
Log.d("BANDERA", "LIVE TRACKING");
Log.d("JSON DEL LIVE TRACKING", jsonParam.toString());
System.out.println("Latitud y longitud" + currentLatitude + currentLongitude);
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
urlConnection.connect();
try {
InputStream is = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
response.append('\r');
}
bufferedReader.close();
if(serverAnswer.contains("open"))
killGps();
serverAnswer = response.toString();
System.out.println("LIVE TRACKING RESPONSE" + serverAnswer);
Log.d("LIVE TRACKING RESPONSE", serverAnswer);
return response.toString();
} catch (FileNotFoundException e) {
Log.d("ERROR: ", "File not found en servidor Response: " + serverAnswer);
}
} catch(Exception e){
e.printStackTrace();
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return serverAnswer;
}
}
If you don't need the entire response, don't store it. Just search each line as you stream it, and exit once you find the text you're looking for:
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("open")) {
killGps();
break;
}
}

Android HttpURLConnection wierd response

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

Android POST Request 400 Response code throws Exception

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

Categories

Resources