Android phone use Java to send a textfile to hosted webspace - java

I want to save a message in a text file on an android phone onto a hosted web server like bluehost of which I have a username and password. I want to store the file in an arbitrary directory on the server.
What are the general strategies that this could be accomplished? I want to use the HTTP protocol, is that a good idea? Is there a better way?

You can try to POST that string to the server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("yourVarName", stringVar);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204);
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}

Transmit a file from an android phone to hosted web space
You import the JSCH jars into your Android application, then you load up the JSCH manager classes and use the defined functions to transmit or receive files between an android phone and hosted webspace.
Run a command over SSH with JSch
JSCH has FTP functionality where you can transmit from phone to hosted web space and will work as long as the hosted web space is reachable by the phone. You can also do the same thing in reverse.

Related

Java - HTTPS Basic authentification with Apache httpclient

I am trying to get some data (json data -> restful server) from a HTTPS server with basic authentification using the Apache httpclient. The SSL certificate is selfsigned.
The server is responding very well to a browser call and also when using curl.
However using the java Apache httpclient, that's another story.
Client side :
The basic authentification is working : the server sends me 401 errors if forget the authorization header or if I set the wrong base64 encoded login:password.
The https/SSL part is working : I am successfully getting data from online restful json server but sadly no way to find an online restful json server with basic authentification for testing purpose...
try {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build()
)
)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
HttpGet getRequest = new HttpGet("https://localhost:5050/getdata");
getRequest.addHeader("Accept", "*/*");
getRequest.addHeader("Authorization", "Basic UBJ0aHVyOmFo0XElYHU=");
HttpResponse response = httpClient.execute(getRequest);
Debugging is telling me :
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
True! It's not a valid HTTP response that I would like to get, it's a valid HTTPS response!
I guess that I am missing something...
Solved!
The error was from the server side : my response did not include any headers....
httpclient seems to like well made responses from a server. That's not true for a browser or for curl : garbage they can receive , display they will !

Upload image from android app gallery to local spring server

Last 3 days I started to learn Spring. I want to send a image from the phone gallery to the spring server. I want to mention that the server is local so I'm using localhost. I saw a tutorial that if I want to send stuff to a local server, the server address is my laptop address + the port (ex. 8080) and I have to connect the phone to the same Wi-Fi as the laptop.
I know how to get the image from the gallery but I don't know how to send it. Many solutions from stackoverflow are old and some classes got deprecated and I can't try their method.
Also, what should I do in the spring controller to receive the image?
You'll have use MultipartFile to upload an image using spring. Please go through following example.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String fileUpload(#RequestParam("file") MultipartFile file) {
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
//save file in server - you may need an another scenario
Path path = Paths.get("/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
//redirect to an another url end point
return "redirect:/upload-status";
}
Please make sure you can reach to your computer through your mobile device. I believe you may know that Android requires additional privilege to use network connections. So make sure you have permitted your app to access network.
EDIT:
You can use HttpClient to upload file from your mobile app. Please try following code.
HttpClient httpClient = AndroidHttpClient.newInstance("App");
HttpPost httpPost = new HttpPost("http://your-server-url");
httpPost.setEntity(new FileEntity(new File("your-file-path"), "application/octet-stream"));
HttpResponse response = httpClient.execute(httpPost);

GCM + Android + Java help need

I am new in the Java Android world. I am working on a course project and I need some help. In my project I have developed an Android app and a Java Socket Server. Android App requests for Keys from Server and server generates keys, Stores them in its DB and sends keys back to android client. This is working fine. Now, in android client, I have to add a button called "Register Device" and on click this should register device with GCM and store the regID in device, which I want to add with keys request and send to server. Server will store the regID in DB with the keys. Then later I want to send a push message to device using that stored regID.
Problems:
How can I store and then access GCM regID to send to server?
What needs to be done in my Socket Server to send push messages to device using stored regID?
As I see you have obtained the deviceID and registrationID and you have to store it on your server.
Now can create a button which will do the following onclick.
$
public void sendRegistrationIdToServer(String deviceId,
String registrationId) {
HttpClient client = new DefaultHttpClient();
Log.d("GCM","sending to server");
HttpPost post = new HttpPost("YOur URL.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Get the deviceID
nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId));
nameValuePairs.add(new BasicNameValuePair("registrationid", registrationId));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Log.d("GCM","sent to server");
} catch (IOException e) {
e.printStackTrace();
}
}
And in the server side you can receive the ID's and store it in your database.
Hope you get it.

How to send data from one webApplication to another

I have two web applications in two different server.I want send some data in header or request to other web application.How can I do that, please help me.
You can pass data by many means:
by making http request from your app:
URLConnection conn = new URL("your other web app servlet url").openConnection();
// pass data using conn. Then on other side you can have a servlet that will receive these calls.
By using JMS for asynchronous communication.
By using webservice (SOAP or REST)
By using RMI
By sharing database between the apps. So one writes to a table and the other reads from that table
By sharing file system file(s)...one writes to a file the other reads from a file.
You can use socket connection.
HttpClient can help
http://hc.apache.org/index.html
Apache HttpComponents
The Apache HttpComponents™ project is responsible for creating and
maintaining a toolset of low level Java components focused on HTTP and
associated protocols.
One web application is functioning as the client of the other. You can use the org.apache.http library to create your HTTP client code in Java. How you will do this depends on a couple of things:
Are you using http or https?
Does the application you are sending data to have a REST API?
Do you have a SOAP based web service?
If you have a SOAP based web service, then creating a Java client for it is very easy. If not, you could do something like this and test the code in a regular Java client before trying to run it in the web application.
import org.apache.http.client.utils.*;
import org.apache.http.*;
import org.apache.http.impl.client.*;
HttpClient httpclient = new DefaultHttpClient();
try {
URIBuilder builder = new URIBuilder();
builder.setHost("yoursite.com").setPath(/appath/rsc/);
builder.addParameter("user", username);
builder.addParameter("param1", "SomeData-sentAsParameter");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() == 200) {
String responseText = EntityUtils.toString(response.getEntity());
httpclient.getConnectionManager().shutdown();
} else {
log(Level.SEVERE, "Server returned HTTP code "
+ response.getStatusLine().getStatusCode());
}
} catch (java.net.URISyntaxException bad) {
System.out.println("URI construction error: " + bad.toString());
}

determine aplication is connected to server or not

I am developing one application which is connecting to server to get some data.
In this I want to check first if application is connected to server or not. And then, if server is on or off? Based on the result I want to do my further manipulations.
So how do I get the result of server status?
Here is the code which I am using:
Code:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.1.23/sip_chat_api/getcountry.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
}
Maintaining session cookies is best choice here, please see how to use session cookie: How do I make an http request using cookies on Android?
here, before sending request to server, check for session cookie. If it exists, proceed for the communication.
Update:
The Java equivalent -- which I believe works on Android -- should be:
InetAddress.getByName(host).isReachable(timeOut)
Check getStatusLine() method of HttpResponse
any status code other than 200 means there is a problem , and each status codes points to different problems happened.
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/StatusLine.html#getStatusCode()

Categories