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.
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'm pretty new to making HTTP connections and working with API's in Java, so I'm not sure where the problem lies. When I send out a POST connection request in order to send a JSON formatted String of text to the other side, I get an error back along with a 400 response code. When I look up that code, it seems my connection isn't properly formatted. Code is below, along with the error message. Please help! Thanks!
public void sendToAPI(String urlPass, String param) throws IOException {
URL url = new URL(urlPass);
HttpURLConnection connectionOut = (HttpURLConnection) url.openConnection();
connectionOut.setRequestMethod("POST");
connectionOut.setConnectTimeout(5000);
connectionOut.setReadTimeout(5000);
connectionOut.setRequestProperty("Content-Type", "application/json");
connectionOut.setRequestProperty("Content-Length", Integer.toString(param.length()));
connectionOut.setDoOutput(true);
connectionOut.setDoInput(true);
connectionOut.connect();
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
stream.flush();
stream.close();
int responsecode = connectionOut.getResponseCode();
if(responsecode != 200) {
System.out.println("Response Code is " + responsecode);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionOut.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
//printing result from response
System.out.println(response.toString());
}
Response Code is 400
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL:XXX
u can try this code:
InputStream inputStream;
if (responseCode == 200) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String lines;
while ((lines = reader.readLine()) != null) {
builder.append(lines);
builder.append(System.getProperty("line.separator"));
}
String retStr = builder.toString().trim();
reader.close();
System.out.println("retStr: " + retStr);
So after playing around with the DataOutputStream, I replaced the below code:
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
With another example I found online:
OutputStream os = connectionOut.getOutputStream();
os.write(param.getBytes());
os.flush();
os.close();
I'm not sure yet why, but this suddenly got the proper response code I was looking for, so the format it was sent in matched what they requested. Thanks for all responses.
I have created a code that checks if user is logged into Facebook. This is how it looks like:
URL url = new URL("https://graph.facebook.com/me?access_token=" + this.fb_token);
System.out.println("Attempting to open connection");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
int responseCode = conn.getResponseCode();
System.out.println(responseCode);
BufferedReader reader;
if(responseCode != 200) {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
}
else{
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}
String json = reader.readLine();
reader.close();
conn.disconnect();
return json;
Next, I parse the Json, check if it's en error or data code and log the user.
My question is: Is if(responseCode != 200) check enough? Can Facebook return a different status code in case of successful authentication?
Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one¶m3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}
I am new to android.So i can any one sho me how to make a http get request such as
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_token="nnch734d00sl2jdk",
oauth_nonce="kllo9940pd9333jh",
oauth_timestamp="1191242096",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"
in android(java)?
You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:
try {
URL url = null;
String response = null;
String parameters = "param1=value1¶m2=value2";
url = new URL("http://www.somedomain.com/sendGetData.php");
//create the connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
} catch (IOException e) {
Log.e("HTTP GET:", e.toString());
}