I am sending data to a server via HTTPUrlConnection. It is received on the server side with PHP code and inserted into a MySQL database. Everything is functioning as intended. The issue is that it using a lot of data to do it. The info I am sending is in the variable unitData which is between 80 and 200 characters long. The data reportedly being used is 3K to 8K of data each transfer. This seem like a lot of overhead to move 200 bytes. I need this to be as small as possible for my application to work, preferably under 500 bytes. Is there a way to tweak HTTPUrlConnection or should I be using Websockets or something else entirely?
class dataSender extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String unitData = params[0];
try {
URL url = new URL("https://www.website.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(10000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//connection.setRequestProperty("Content-Length", "" + test.length());
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes ("mydata="+unitData);
wr.flush ();
wr.close ();
//Get Response
int responseCode = connection.getResponseCode();
StringBuffer response = new StringBuffer();
if(responseCode == 200) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
else{
response.append("Error:");
response.append(responseCode);
}
connection.disconnect();
return response.toString();
//return "nada";
} catch (Exception e) {
//Toast.makeText(getApplicationContext(), "exception:"+e, Toast.LENGTH_SHORT);
return e.toString();
}
}
}
Related
I'm connecting with two local servers post parameters for redirect link. But not change url and web view after posting the parameters. I get only response.toString() (html string like ...."). How I change redirect link and view.
I found other questions and answers that are not easy to understand.
try {
HttpURLConnection connection = null;
URL url = new URL("http://localhost:9090/myproject/payreq");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", ""
+ Integer.toString(postParams.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
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');
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
I expect change my project link's 8080 from redirect follow other sites.
If you want to redirect to a different server, completetely on the server side, without the user noticing a change in the browser URL, use forward: redirection:
#Controller
public class MyController {
#RequestMapping("/myurl")
public String redirectWithUsingForwardPrefix(ModelMap model) {
model.addAttribute("attribute", "forwardWithForwardPrefix");
return "forward:/http://localhost:9090/myproject/payreq";
}
}
I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.
I 'm using the following code to post value variables to a server:
protected String doInBackground(String... params) {
try{
URL url= new URL(params[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data= URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8");
post_data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[2], "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
Here is the async-task call:
BackgroundWorker backgroundWorker= new BackgroundWorker(this);
backgroundWorker.execute("http://...", "somename", "somesurname");
The code runs fine (no errors), however I'm not able to see any data in my database (.php is also working correctly-double checked).
What could be the issue here?
I would suggest using volley instead, here's a good and easy tutorial: http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
But here is how I used httpURLConnection:
public String executePost() {
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(/*URL HERE*/);
String urlParameters = "/*THE PARAMS. YOU KNOW THIS ;) */";
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//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');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I added this method to my MainActivity.java
But i'm getting error on the static: Inner classes cannot have static declatarions.
protected static String excutePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
java.io.InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new java.io.InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
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();
}
}
}
I can remove the static and then i'm getting no errors.
But where do i call this method from now ? From inside the onCreate ?
Tried but it's not exist when i type excute....in the onCreate it's not exist can't call it.
How do i use this method ? And what should i put as urlParameters ?
The outer class which holds the "excutePost" is an inner class therefore it cannot have static methods in it. What you can do is move the outer class to a separate file and make it non static - this will solve your problem.
I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....