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....
Related
When I Debug my code get Response code 200 which means success. Then also I'm getting null response.
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 have Tested My API in postman its Working with response code 200 and giving Response in json format but in my code its not working .
Hope you will understand my problem.
Thank you very much for your time and assistance in this matter.
The problem is probably from this line:
String query = builder.build().getEncodedQuery();
You need to use:
String query = builder.build().toString();
This is because getEncodedQuery() is only returning the query, from the documentation:
String getEncodedQuery ()
Gets the encoded query component from this URI. The query comes after the query separator ('?') and before the fragment separator ('#'). This method would return "q=android" for "http://www.google.com/search?q=android".
UPDATED
You're building the query after opening the connection, hence you having the error.
You need to build the url with the query first:
Uri uri = Uri.parse("http://ishook.com/users/friends/send_friend_request_json/")
.buildUpon()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
.build();
URL url = new URL(builtUri.toString());
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
Note: I haven't test the code. So, don't expected it working automagically.
/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;
}
}
I'm trying to send POST request via HttpURLConnection, here is the code
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
responseCode is 200 which means everything went OK, however it says Undefined index: id
id is well defined inside php file
$user = User::find_by_id($_POST['id']);
echo json_encode($user);
and it works fine when I send post request from an html file yet when i send it from application it says id undefined which means that POST data is not sent.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
this is how i instantiate asynctask object inside main activity
UPDATE: when i send not encoded string it works fine!
writer.write("id=5"); // works perfectly!
what is wrong with URLEncoder i use in the code?
I believe you have a problem in this line:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
You are url-encoding the = as well as the params, that's why the server cannot recognise the form fields. Try to encode the params only:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
The reason is that URL encoding is for passing special characters like = in the value(or key). Basically, the server will split and parse the key-value pairs with & and = before doing the decoding. And when you url-encode the = character, the server simply couldn't recognise it during the split and parse phase.
When i need to communicate with the server i use this
Server Class
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
OtherClass
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
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();
}
}