Android app uploading data to a python server via post - java

I have successfully implemented this from android to a java httpservlet on google app engine, but I'd like to use python instead for the server side. I'm new to python. Has anyone done this? I have the guestbook example up and running, but I can't seem to send posts from my android app to the server.
I'd also like to issue a string response back to the client like "success".
A guiding hand would be much appreciated.
Thanks
***Client side java:
URL url = new URL(Const.SERVER_NAME);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream()
);
out.write("content=12345");
out.close();
***Server side Python:
class Upload(webapp.RequestHandler):
def post(self):
greeting.content = self.request.get('content')
greeting.put()
***Server side Java (working)
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
String instring = request.getParameter("content")
// set the response code and write the response data
response.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write("Success");
writer.flush();
writer.close();
} catch (IOException e) {
try{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(e.getMessage());
response.getWriter().close();
} catch (IOException ioe) {
}
}

I know it's been a long time. But I did solve this so I'll post the solution.
Android code:
url = new URL(SERVER_URL);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
String post_string;
post_string = "deviceID="+tm.getDeviceId().toString();
// send post string to server
out.write(post_string);
out.close();
//grab a return string from server
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
Toast.makeText(context, in.readLine(), Toast.LENGTH_SHORT).show();
And here's the python server side, using Django with GAE:
def upload(request):
if request.method == 'POST':
deviceID = measurement.deviceID = str(request.POST['deviceID'])
return HttpResponse('Success!')
else:
return HttpResponse('Invalid Data')

Related

Android error: java.net.SocketException Socket is closed

I get java socket is closed exception meanwhile I am trying to read the response that I got from my web service. My web service sends a JSON as a response and the http code response is always 200 but I do not know if the response String is so long that BufferedReader crash when I try to use readLine(). If the issue is my response size, there is another way to get my json response?
I already used postman to be secured that my web service is working without problems, so I get my json responde as I want.
I use this same format of code to call other web services that I have and I do not have this issue. And actually, this code worked well before, since yesterday that I have this problem.
The error arises in the while below
try {
url = new URL(ws);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
//HEADERS
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "Mozilla/5.0" + " (Linux; Android 1.5; es-ES) Ejemplo HTTP");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
bufferedWriter.write(jsonObject.toString());
bufferedWriter.flush();
bufferedWriter.close();
int response = connection.getResponseCode();
connection.disconnect();
StringBuilder result = new StringBuilder();
if (response == HttpURLConnection.HTTP_OK) {
InputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
if (!result.toString().equals("null")) {
JSONArray jsonResult = new JSONArray(result.toString());
if (jsonResult.length() > 0) {
//code to use JSON response info
} else {
//code to show alert dialog error
}
} else {
//code to show alert dialog error
}
} else {
//code to show alert dialog error
}
} catch (Exception e) {
Log.i("JSONWSResponse error: ", e.toString());
//code to show alert dialog error
}

How to display android POST string on PHP server?

I am trying to send json string from my android app to my php server. Below is the complete code from my mobiledb_control.php and httpconnect.java
The Log.v("HTTPSENDER","WORKED"); runs, and I get no errors.
However my error_log("in"); does not run.
How do I display the JSON sent via android into my error_log() ?
HttpConnect.java:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
}catch(Exception e){
e.printStackTrace();
}
}
}
mobiledb_control.php:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/error.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
$headers = apache_request_headers();
?>
try this in PHP code
and turn on error reporting like this
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
and
print_r($_POST);
for more clarification what you are getting from post.
use encode and decode functions of php for making and parsing json.
$request=json_decode($_POST['json']); // it gives the Array
foreach($request as $values){
echo($values['your_value1'])
echo($values['your_value2'])
}
please refer this url : http://php.net/manual/en/function.json-decode.php
Seemed to have fixed it but I have no idea how
PHP File:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/location.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
?>
JAVA File:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
Log.v("HTTPSENDER",""+conn.getResponseCode());
}catch(Exception e){
e.printStackTrace();
}
}
}
In designing server-client communication, it is imperative to make sure both client and server can communicate with each other. With that in mind, can you please provide the server response code by adding this in your code inside try block:
try {
...
Log.d(TAG, "code: " + conn.getReturnCode());
InputStream is = conn.getInputStream();
String serverReply = readIt(is, 500);
Log.d(TAG, serverReply);
...
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
It will return 200 and 401 respectively. Returns -1 if no code can be
discerned from the response (i.e., the response is not valid HTTP).
Cheers!

httpsurlconnection posts string wrongly in java application

In my java application I used a Httpsurlconnection to post some string data to the server. When I test this code on android, it works perfectly. However, in a java application it does not work. Client java application is as follows:
public static void main(String[] args) {
disableSslVerification();
new HttpsClient().testIt();
}
private void testIt() {
String https_url = "https://XXX.XX.XXX.XXX:XXXX/XXXXX/TestServlet";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
print_content(con, "test");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void print_content(HttpsURLConnection connection, String data) {
if (connection != null) {
try {
connection.setConnectTimeout(6000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
Charset cSet = Charset.forName("UTF-8");
byte bytes[] = data.getBytes(cSet);
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(bytes.length));
connection.setRequestProperty("Content-Language", "tr");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.write(bytes);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, cSet));
String line;
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append(System.getProperty("line.separator"));
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
And the servlet is as follows:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s = getHTML(request);
try {
out.print("received data:");
out.print(s);
} finally {
out.close();
}
}
private String getHTML(HttpServletRequest request) throws IOException {
int n = request.getContentLength();
if (n < 1) {
return "";
}
byte bytes[] = new byte[n];
request.getInputStream().read(bytes);
return new String(bytes, "UTF-8");
}
When I run this application, servlet's response is:
received data:t☐☐☐
Always only the first character is correctly send to the servlet. The same code works perfect on android. Can anyone help me please? Thanks...
I can't see an obvious problem with your code that would cause this.
Can anyone help me please?
I suggest that you take a methodical approach to investigating the problem. Use a packet sniffer to check what is actually being sent over the wire. Check that the actual headers in the request and response are correct. Check that the request and response bodies are really properly encoded UTF-8 ...
What you find in your investigation / evidence gathering will help you figure out where the problem (or problems) are occurring ... and that will allow you to home in on the part(s) of your code that is/are responsible.
request.getInputStream().read(bytes);
You might need to do this read in a loop. At the very least, check how many bytes have been read. The array appears to be empty except for the first char.
Reads some number of bytes from the input stream and stores them into
the buffer array b. The number of bytes actually read is returned as
an integer. This method blocks until input data is available, end of
file is detected, or an exception is thrown.

Download XML to string

I tried to download XML by using the code below:
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://xx.xx.xx.xx/1.xml");
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
Log.e(DEBUG_TAG, "6",e);
} catch (IOException e) {
Log.e(DEBUG_TAG, "7",e);
}
return "error";
}
and I am getting the error:
12-12 08:12:15.434: ERROR/myLogs(10977): java.io.FileNotFoundException: http://xx.xx.xx.xx/1.xml
If I open this url in browser is see:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Home>
<Child sex="male" age="5" name="Vasya"/>
<pets>
<Dog age="3" name="Druzshok"/>
</pets>
</Home>
I guess your server intercept some request .
for example :
check [User-Agent] in headers.
ucon.setRequestProperty("Accept", "application/xml"); remove the line..
You are wondering why the java URL object throws a file not found? It means the server responded to your request with a "404 not found" or for whatever reason no response was given by the server.
So you are wondering why that when you visit it in the browser it works fine, because the browser is treated differently by the server than your script. First try setting the user-agent to be the same as your browser. Servers are cracking down on robots more and more these days because of impolite script writers banging on their websites.
Source:
java.io.FileNotFoundException for valid URL
maybe server filter ['User-Agent'].
code:
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://xx.xx.xx.xx/1.xml");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setReadTimeout(60 * 1000);
conn.setConnectTimeout(30*1000);
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0) Gecko/20100101 Firefox/39.0");
BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
StringBuilder buf = new StringBuilder(512);
String line = null;
while((line=reader.readLine())!=null){
buf.append(line).append("\n");
}
conn.disconnect();
return buf.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Using HTTP Post between 2 Java servlets

I have setup a java servlet which accepts parameters from the URL and have it working properly:
public class GetThem extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
try {
double lat=Double.parseDouble(request.getParameter("lat"));
double lon=Double.parseDouble(request.getParameter("lon"));
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(lat + " and " + lon);
} catch (Exception e) {
e.printStackTrace();
}
}
}
So visiting this link:
http://www.example.com:8080/HttpPost/HttpPost?lat=1&lon=2 would output:
"1.0 and 2.0"
I'm currently calling it from another java program using this code:
try{
URL objectGet = new URL("http://www.example.com:8080/HttpPost/HttpPost?lat=" + Double.toString(dg.getLatDouble()) + "&lon=" + Double.toString(dg.getLonDouble()));
URLConnection yc = objectGet.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
...
Now I want to change it so that I'm not using the URL parameters to pass this data to the server. I want to send much larger messages to this server. I am aware that I need to use http post rather than http get to achieve this but am not sure how to do it.
Do I need to change anything on the server side which is receiving data? What do I need to do on the client side which is posting this data?
Any help would be greatly appreciate thanks.
Ideally I'd like to send this data in JSON format.
Below there's sample from the first link found by "java HTTP POST example" in google.
try {
// Construct data
StringBuilder dataBuilder = new StringBuilder();
dataBuilder.append(URLEncoder.encode("key1", "UTF-8")).append('=').append(URLEncoder.encode("value1", "UTF-8")).
append(URLEncoder.encode("key2", "UTF-8")).append('=').append(URLEncoder.encode("value2", "UTF-8"));
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(dataBuilder.toString());
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
I think you should be using HTTPClient instead of handling connections and streams. Check http://hc.apache.org/httpclient-3.x/tutorial.html

Categories

Resources