Android can't access a web server? - java

So I've got a little script set up on my server that says whether a user is log in able or not. When accessing the url http:server-url/username/password/ I would get a string returned called "correct" or "incorrect".
What I'm doing in my Android app is the following:
HttpClient httpclient = new DefaultHttpClient();
String url = "http://server-url/"+usernameText+"/"+passwordHash+"/";
HttpPost httppost = new HttpPost(url);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
String response = httpclient.execute(httppost, handler);
Log.e("logged in",response);
} catch (ClientProtocolException e) {
Log.e("clientprotocolexception",e.toString());
} catch (IOException e) {
Log.e("ioexception","error");
}
I'm getting an error:
04-29 14:31:15.728: ERROR/clientprotocolexception(9366): org.apache.http.client.HttpResponseException: FORBIDDEN
but the website itself works fine when I just access it through the browser? Are these some settings I have to set correctly somewhere on the server, or am I forgetting something in my code?
Thanks!

Did you think of giving the internet permission?
<uses-permission android:name="android.permission.INTERNET"/>

I was using Post instead of Get, JCs answered it in the comments on my original question.

Use this example to guide you to pass username password and credentials, instead of using the url.

Related

HTTP post request doesn't respond on production environment (war with tomcat server)

I have implemented a PerformHttpPostRequest function which is supposed to send a post request contains a JSON type body and get a JSON response via Apache HttpClient.
public static String PerformHttpPostRequest(String url, String requestBody) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(requestBody);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
return (new BufferedReader(new InputStreamReader(is, "UTF-8"))).readLine();
}
The problem is, the code works perfect on developing environment, but when running the war file with a tomcat server but the request is not executed.
I've tried adding several catch blocks such as IOException, Exception and the code doesn't get there.
I've added debug prints which demonstrated that the code stops responding at the client.execute(...) command.
The function is called inside a try block, and after executing the .execute(...) command the code does get to the finally block.
I've already searched for a similar problem and didn't find an answer.
Is it a known issue? Does anyone have any idea of what can cause that? Or how can I fix it?
Hi Talor nice to meet you,
Please try to use HttpURLConnection to solve this issue like so:
Java - sending HTTP parameters via POST method easily
Have a nice day.
el profesor
I have tried with RestTemplate.
RequestObject requestObject = new RequestObject();
requestObject.setKey("abcd");
requestObject.setEndpoint(serviceEndPoint);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<RequestObject> requestBody = new HttpEntity<RequestObject>(
requestObject);
ResponseEntity<RequestObject> result = restTemplate.postForEntity(
serviceEndPoint, requestBody, RequestObject.class);
Its very simple and hassle free, hope it helps
Few things you can try out.
- Try to do ping/curl from that box where you are running tomcat.
- Try to have a test method which make a get request to a server which is always reachable. For ex google.com and print the status. That way you could be able to know that you code is actually working or not in server env.
Hope this helps. :)
If the code doesn't pass beyond client.execute(...) but it does execute the finally block in the calling code, then you can find out what caused the aborted execution by adding this catch block to the try block that contains the finally:
catch(Throwable x) {
x.printStackTrace();
}
Throwable is the superclass for all exception and error classes, so catching a Throwable will catch everything.

Does anyone have an updated example on posting a JSON request?

I am having a mess of a time finding up to date information on sending a JSON request to a local server. I keep coming across examples that use deprecated code, and I'd really like to do this with code that isn't.
I can at least say that I now have a working example, and I am not receiving any deprecated messages from NetBeans, but I would like to know if what I've put together is the right way:
public void sendUpdateRequest() {
String updateString =
"{\"jsonrpc\": \"2.0\", \"method\": \"VideoLibrary.Scan\"}" ;
StringEntity entity = new StringEntity(updateString, Consts.UTF_8);
HttpPost httpPost = new HttpPost(getURL()); // http://xbmc:xbmc#10.0.0.151:8080/jsonrpc
entity.setContentType("application/json");
httpPost.setEntity(entity);
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine()); // move to log
}
catch (IOException e) {
e.printStackTrace(); // move to log
}
}
This is something I'm working on to update XBMC with a JSON HTTP request
Edit
Changed the code to try with resources per the comment -- hopefully this will be useful for someone else dealing with JSON and Java
but I would like to know if what I've put together is the right way:
Yes, you are doing it correctly given the details you've posted.
The StringEntity contains the body of the request. You can set any appropriate headers there. Any other headers can be set directly on the HttpPost object.
As stated in the comments, don't take any chances, close() the CloseableHttpClient in a finally block.

Server - Client connection between android app and a server

I'm developing a Java Server Aplication and an Android Aplication and my android app need to send and receive data from/to server (Bidirectional), for example my Android App need to Login to the server and the server need to know who is logged in.
Wich protocol do you recommend me to do this kind of program?
Usually in this situation you can use HTTP protocol for several reason. First of all you can reach your server even if it is behind a firewall or something like that.
Second using HTTP you can send XML or JSON data widely used in android.
The only limitation you have is the HTTP protocol is a synchronous protocol so you send and wait for the answer.
Using HTTP you can use your existing server architecture and you can wrap your business layer with a Webservices so that you can expose your services.
If you need that server can contact your app you can use you can use Google Cloud Mesaging.
Use Http request (get or post request) to communicate with a server.
You have to use a thread or an AsyncTask to perform your request or the execution fails from Api 11+.
I attach an example of http request that receives an xml:
import org.apache.http.*;
[..]
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.d("XMLParser-getXmlFromUrl", "UnsupportedEncodingException");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("XMLParser-getXmlFromUrl", "ClientProtocolException");
e.printStackTrace();
} catch (IOException e) {
Log.d("XMLParser-getXmlFromUrl", "IOException");
e.printStackTrace();
}
// return XML
return xml;
}

Calling Soap webservice from android

I am using the below process,
1)Create a String template for a SOAP request and substitute user-supplied values at runtime in this template to create a valid request.
2) Wrap this string in a StringEntity and set its content type as text/xml
3) Set this entity in the SOAP request.
and with the help of httppost I am posting the request,
I am using a demo webservice from w3schools.com
url--->
http://www.w3schools.com/webservices/tempconvert.asmx
What I have tried is,
HttpPost httppost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx");
StringEntity se;
try {
SOAPRequestXML="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/><soapenv:Body><tem:CelsiusToFahrenheit><!--Optional:--><tem:Celsius>30</tem:Celsius></tem:CelsiusToFahrenheit></soapenv:Body></soapenv:Envelope>";
Log.d("request is ", SOAPRequestXML+"!!!");
se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
t.setText(EntityUtils.toString(resEntity));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am able to get the response in soapui, so surely the code is wrong because in emulator I am getting the output,
"the server cannot service the request because the media type is unsupported".
Am I passing the correct parameter in the constructor of HttpPost or am I making the correct xml request.I tried a lot but could not figure it out.
Thanks
The only problem with your code is you are setting Header as,
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
instead of,
httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
As you can see the request in the URL that is -> w3schoools, they are using,
Content-Type: text/xml; charset=utf-8
and you where not passing the same content type. So, it was giving you error as,
The server cannot service the request because the media type is unsupported.
So, just change the Header and you will get the desired response.
I have written an article on How to Call Web Service in Android Using SOAP at c-sharpcorner.com.
So many person get helped from that article. You can also download it and run. I will help you to understand how to use SOAP for web service.
Edit
Take a look at following links. It has complex data handling with ksoap.
Complex objects tutorial with sample code
http://bimbim.in/post/2010/10/08/Android-Calling-Web-Service-with-complex-types.aspx
http://seesharpgears.blogspot.in/2010/10/web-service-that-returns-array-of.html
I have a hunch that the emulator android version and the phone version are different.
But I have few suggestions. Use following:
httppost.setHeader("Accept-Charset","utf-8");
httppost.setHeader("Accept","text/xml,application/text+xml,application/soap+xml");
similarly, set content type as all of the above.
Have you tried using the ksoap2 library for Android ?
you can find it here, give it a shot :
https://code.google.com/p/ksoap2-android/
Hope this helps !
This way the html form is posting 123 celsius. No SOAP or envelops, just working:)
try {
HttpPost httppost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit");
StringEntity se = new StringEntity("Celsius=123");
httppost.setEntity(se);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = new DefaultHttpClient().execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();
return EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}

What is the preferred method for uploading to a server from Android?

I've been trying to find a way to upload a video from an Android device to an API, but I haven't found a good way to do it. It seems most of the information I've found online is fairly out of date (a lot of it being from last year). Most of them are using a method like this: http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
What's the easiest/preferred way to upload something to an API with a multipart POST?
I have an Android app I'm developing against the Campfire chat service's "API". The code here uploads a file through multipart POST:
http://github.com/klondike/android-campfire/blob/master/src/com/github/klondike/java/campfire/Room.java#L175
Everything after the "dos.close()" line is related to checking the response to detect whether the post was successful.
Not everything in there is necessary for every multi-part post; for example, the X-Requested-With header is specific to Campfire, the User-Agent is optional, and the Cookie is because I have to stay logged in. Also, the "OH MY GOD" comment about spacing is probably Campfire-specific.
I've heard that the latest version of the HttpClient library from Apache has more convenient built-in multi-part support, but the last sync Google performed against it to Android didn't include those features, so here I am doing it manually.
Hope that's of some help.
You could use the HttpClient from the Apache Software Foundation. It is part of the Android API:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.somewebpage.com/site-that-can-handle-post");
try {
MultipartEntity entity = new MultipartEntity();
entity.addPart("timestamp", new StringBody("1311789946"));
entity.addPart("image", new FileBody(new File("/foo/bar/video.mpeg")));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
Log.v(MyActivity.TAG, "doh!", e);
}
Hope that helps. :)

Categories

Resources