Use webservice in Android - java

I need to send data to a web service that is write in c# .net,
if I use a c# program it can get the names of the web service and
the function that I can use I guess cause it's java it can't do the same
as c#, if someone know how to do this it's will be great.
thanks for the help!
I use httpURLConnection and write this code to send and get the response
from connection.
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + '\n');
}
Log.i("","here "+sb.toString());
return sb.toString();
} catch (Exception e) {
Log.i("","problem in connection");
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

If I'm not mistaken, C# web services uses SOAP protocol, so you'll probably need to parse the soap response which will give the information about the web service api:
check this thread:
Parsing SoapObject Responst in android

Related

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

FatalShutdown in Android with httpurlconnection

I'm actually srugling with my application using HttpUrlConnection, I tried the simplest code found on the internet and still got a FatalShutDown in the logcat and I don't understand the problem.
Here is the code :
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
response_textview.setText(total.toString());
urlConnection.disconnect();
}
catch (MalformedURLException e){
response_textview.setText(e.getMessage());
}
catch (IOException e){
response_textview.setText(e.getMessage());
}
And I got this in the logcat :
Thanks
Wrap your code with Asynktask doInBackground() method.
You need to make request in new thread. Probably, your code (it is only try catch) is running on main thread. This operation is denied. Try to use e.g. Thread.class to make request in new thread.
You shouldn't perform network operation on main thread. Use AsyncTask.
1. Create AsyncTask object and move your code into doInBackground method as mentioned below:
AsyncTask task = new AsyncTask<Void,String,String>(){
#Override
protected String doInBackground(Void... params) {
// perform your network operation here and return response
try {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
urlConnection.disconnect();
}
catch (MalformedURLException e){
return e.getMessage();
}
catch (IOException e){
return e.getMessage();
}
return total.toString();
}
protected void onPostExecute(String response){
// response returned by doInBackGround() will be received
// by onPostExecute(String response)
response_textview.setText(response);
}
};
2. Execute task
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

HttpURLConnection always failing with 401

I'm trying to use HttpURLConnection for connecting to server from Android app which I'm developing. For now, I'm testing the connection code not in an app but as a plain java program with main class. I guess this doesn't make any difference as far as HttpUrlConnection.
Please examine the code snippet. Another issue is even errorStream is throwing null. This I feel is because of malformed URL.
private static String urlConnectionTry() {
URL url; HttpURLConnection connection = null;
try {
String urlParameters = "email=" + URLEncoder.encode("email", "UTF-8") +
"&pwd=" + URLEncoder.encode("password", "UTF-8");
//Create connection
url = new URL("http://example.com/login");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("uuid", getUuid());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
private static String getUuid() {
try {
Document doc=Jsoup.connect("http://example.com/getUuid").get();
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
if(metaElem.attr("name").equals("uuid")) {
return metaElem.attr("content");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You're probably receiving 401 because the credentials that was sent to the server is not authorized- it's probably not registered or the password is incorrect.
As for the null error stream, take a look at this SO answer.
If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null.
It is probably better if you check first the response code using HttpUrlConnection#getResponseCode(). Decide on whether you'll be checking the contents of the error stream based on the response code you get.

Send HTTP POST - Android

I know that this has been asked but most are out dated, and method are deprecated. I have found this solution,
new Thread( new Runnable() {
#Override
public void run() {
try {
String query = "param=" +"item"+"&other="+"num";
URL url = new URL("http://www.url.com/url_post.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.toString());
}
}
}).start();
But, it does not provide how to get data that is returned for example, I am return some JSON, where get I get that data that is returned?
Thanks for the help :)
Do this
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
Finally in response you will get response JSON string then do what you want to do.
For more details visit this link
http://www.xyzws.com/javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
I recommend you to use this project as library:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
It's extremely easy and I use it for all my projects. I commited it to Github because it is difficult for me to find an easy Rest client for general purpose.
I'm going to commit an update for integration with Android Studio ASAP.
I hope it helps!!
InputStream in = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Add this part after your writer.close()
connection.connect();
int statusCode = connection.getResponseCode();
Log.d("ON POST", " The status code is " + statusCode);
if (statusCode == 200) {
is = new BufferedInputStream(connection.getInputStream());
String response = convertInputStreamToString(is);
Log.d("ON POST", "The response is " + response);
return response;
} else {
Log.d("ON POST", "On Else");
return "";
}
The ConvertInputStreamToString() should be created to return your json as string
public static String convertInputStreamToString(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}

network timeout exception in android

I developed android app and tested in Samsung tab 2.The code fetch the data from java server page which hosted in server.It works day before,but now it shows network time out exception during urlConnection.getInputStream() .I d't change anything in my code. pls help me to overcome the error.
try {
String tally_ipaddr="XXXXXXX";
URL url = new URL(tally_ipaddr+"/Iplogin.jsp");
urlConnection = (HttpURLConnection) url.openConnection();
String line = "";
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line);
}
Toast.makeText(MyActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(MyActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
class UrlFetch extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String tally_ipaddr="XXXXXXX";
URL url = new URL(tally_ipaddr+"/Iplogin.jsp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 5 seconds
conn.setRequestMethod("GET");
conn.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
conn.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
and call the asynctask like given below
new UrlFetch().execute();
Hope the above code will works for you
I notice the address ends with "Iplogin.jsp".
Make sure the server is accepting connections from the IP address of your device. I think the IP address of your device has changed and the server is no longer responding to requests from that device.
The fact that you can access the service from your desktop browser but NOT from the device browser is highly suspect.

Categories

Resources