I recently wrote some code in java that is supposed to send a string to a php script and it works perfectly fine. However it refuses to work when i use it in an android program. thought someone could help me find out what the problem is!
public static String main(String x, String y){
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}else{
try{
String username = x;
String password = y;
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
// LÄSER FRÅN HEMSIDAN
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
//AVSLUTA CONNECTION
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(Exception e){
e.printStackTrace();
}
}
return null;
}
I did allow internet permission in the manifest by adding
<uses-permission android:name="android.permission.INTERNET" />
but it simply gives me no result. At first i thought that maybe there was something missing in the php script but it works perfectly fine when being tested in eclipse, so there must be something wrong or missing from the android part, right?
Make sure your else block executes.
That's a VERY bad practice - use Retrofit library for consuming REST apis instead. http://www.vogella.com/tutorials/Retrofit/article.html
Related
I am trying to create my first android application that utilizes a REST api. My api is written in Node.JS and has already been tested using Postman, however, I am having trouble sending JSON data to my api.
#Override
protected String doInBackground(String... params) {
String data = "";
String urlName = params[0];
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
I always reach the line that declares and initializes my DataOutputSteam and doesn't execute the code. I am not even getting a log that my Virtual device has visited my server at all.
I have included in the manifest XML both of these already.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Based on your logs, you're hitting a NetworkOnMainThreadException and that's preventing the network request from being executed (it's going into your catch block instead). This suggests you aren't calling your AsyncTask correctly - ensure that you're calling execute instead of calling doInBackground. See also here for more information on this general pattern.
Try this, it is for POST method that accept 2 parameter email and password.
Change it based on your requirement
URL url = new URL(Login_url);
HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept" , "application/json");
conn.connect();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", "Your_Email")
.appendQueryParameter("password","Your_Password");
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();
code = conn.getResponseCode();
Log.e("Result", code + "");
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);
}
Log.e("Result",result.toString());
I don't know why HttpURLConnection fails on android but succeeds in java Eclipse. I have been facing that problem for many days and trying to solve it but have never pass it. The code in my case as followings:
try {
url = "https://mobitrade.vpbs.com.vn:8080/getlistckindex/hnx";
URL urlGetSymbol = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlGetSymbol.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(15000);
con.setConnectTimeout(15000);
con.setDoOutput(true);
con.connect();
int responseCode = con.getResponseCode();
BufferedReader in =new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseString = response.toString().replaceAll("\\[", "").replaceAll("\\]", "")
.replaceAll("\"", "");
} catch (IOException ioe) {
ioe.printStackTrace();
}
The code works fine in java eclipse but don't work on android due to con.connect() gets error.
I think you are using different api packages for HttpURLConnection so please check that. you can use java.net.HttpURLConnection api for the same.
Add
<uses-permission android:name="android.permission.INTERNET"/>
to your Androidmanifest.xml
When i redirect android app to my local xampp server i am getting expected output from server. like below
Problem is when i redirect my app to a real ip or a domain server problem occurs. Here is my code.
protected String doInBackground(String[] paramparameterForURL) {
try{
//serv_url="http://www.eurekabd.com";//shakil/"+paramparameterForURL[0];
URL url = new URL("http://www.eurekabd.com/shakil/home.php"/*serv_url*/);
//URL url = new URL("http://192.168.0.109/shakil/shakil.php"/*serv_url*/);
//URL url = new URL("http://144.48.2.11/shakil/shakil.php"/*serv_url*/);
JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "abhay");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(300 /* milliseconds */);
conn.setConnectTimeout(300 /* milliseconds */);
//conn.setRequestMethod("GET");
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 in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
Problems are
1.Server WWW.eurecabd.com is returning exception NULL like below
2.real ip server is returning empty like bellow
How to solve the issue or what is the issue? Is it in coding or in network protocol?
The issue is the response of the different servers , also you should modified this :
conn.setConnectTimeout(300 /* milliseconds */);
300 milliseconds is too low for a connection timeout , remember is in milliseconds.
In my android application am reading text file which is in server.
Am using below method.
private String getUrlContents(String UrlOfFile)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(UrlOfFile);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
Log.d(TAG,"Exception >>>"+Log.getStackTraceString(e));
}
return content.toString();
}
But I am getting previous value of text file. When I once do clear data of app its able to get actual value.
Please help me to solve this issue.
My problem was due to returning of cached response.
Issue solved by urlConnection.setUseCaches(false);
Thanks to all responds,
How to prevent Android from returning a cached response to my HTTP Request?
Adding header for HttpURLConnection
i asked this same question yesterday but i was not too clear about what i wanted the function to do, so i thought that i'd might give it another try!
i want to send data from a java program to a mysql server that i'm currently hosting via a local xampp server. Since this java class is will be used by a code written in android (also swift) it wont be possibe (atleast without a headache) to use a jdbc driver, therefor i'm trying to pass data to a php server with the help of java POST.
The problem is that literally nothing happens when i run the code. no errors, no data is being added to the sql, nothing is happening. So maybe a better programmer than be can have a look at my code and maybe see an issue that i currently can't!
Java code:
public static String main(String x, String y){
try{
String username = x;
String password = y;
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
// LÄSER FRÅN HEMSIDAN
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
PHP
<body>
<?php
$db_name = "smoothie";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$usr = $_POST["username"];
$pass = $_POST["password"];
$conn = mysql_connect($server_name,$mysql_username,$mysql_password,$db_name);
$query = "INSERT INTO members (username, password)
VALUES ('$usr','$pass')";
?>
I could really use some help here!! :)