1
I was using Python to update some equipment via Post, where I defined some parameters and sent a file, where the equipment itself updates after receiving this file. However, as I developed a Java application with Swing, I was unable to implement file uploading and parameters with the libraries I found.
This is the code I use to send the parameters and file to the equipment:
def Post(host,user, password, (param), files):
url = 'http://'+host+'/cgi-bin/firmware.cgi'
session = requests.session()
ses = session.get(url)
req1 = session.post(url, data = ({'formNumber' : '201', 'user' : user, 'password' : password}))
req2 = session.post(url, files=files, data=param)
print req2.content
print session.cookies
Can anyone tell me how I could do this in Java?
Edited:
I was able to send the file via Post in java, however, I found another problem. When I send the file, after the upload has finished, the device restarts, that is, I have no confirmation that the file was sent in full or not.
Is there any way to check if the file has been sent in full?
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
public class PostFunction {
private static final String FORM_NUMBER_LOGIN = "201";
private static final String FORM_NUMBER_UPDATE_FIRMWARE = "101";
private String user;
private String password;
private String url;
private HttpClient client;
static int result;
private static final Logger LOGGER = Logger.getLogger(PostFunction.class.getName());
public PostFunction(final String url, final String user, final String password) {
this.user = user;
this.password = password;
this.url = url;
this.client = HttpClientBuilder.create().build();
}
/**
*
* Metodo para fazer atualizacao de firmware do equipamento.
*
* @param file
* Arquivo de Firmware
* @return Resposta de confirmacao
*/
public Boolean updateFirmware(File file) {
try {
LOGGER.log(Level.INFO, "loginPost INIT");
this.loginPost();
LOGGER.log(Level.INFO, "loginPost END");
LOGGER.log(Level.INFO, "sendFilePost INIT");
this.sendFilePost(file);
LOGGER.log(Level.INFO, "sendFilePost END");
} catch (ClientProtocolException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return false;
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return false;
}
return true;
}
private void sendFilePost(File file) throws ClientProtocolException, IOException {
try {
HttpEntity entity = MultipartEntityBuilder.create().addTextBody("formNumber", FORM_NUMBER_UPDATE_FIRMWARE)
.addBinaryBody("btnBrowse", file, ContentType.create("application/octet-stream"), file.getName())
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
System.out.println(response);
InputStream body = response.getEntity().getContent();
String outResponse = getStringFromInputStream(body);
} catch (IOException e) {
e.printStackTrace();
}
}
private void loginPost() throws ClientProtocolException, IOException {
try {
int count = 0;
HttpPost httpPost = new HttpPost(this.url);
// add header
httpPost.setHeader("User-Agent", "Mozilla/5.0");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user", user));
urlParameters.add(new BasicNameValuePair("password", password));
urlParameters.add(new BasicNameValuePair("formNumber", FORM_NUMBER_LOGIN));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(httpPost);
InputStream body = response.getEntity().getContent();
String outResponse = getStringFromInputStream(body);
if (outResponse.contains("login")) {
this.loginPost();
LOGGER.log(Level.INFO, "Tentativa" + count++);
}
} catch (IOException e) {
e.printStackTrace();
}
// LOGGER.log(Level.INFO, "LOGOU!");
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
result = 0;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
// sb.append(line.trim());
System.out.println(line);
if (line.trim().equals("id = setTimeout( \"start()\", 1000 );")) {
LOGGER.log(Level.INFO, "Update OK");
result = 1;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
int resulting() {
return result;
}
}
This is the stack in English, translate your question.
– user28595
Sorry buddy, translated.
– Lucas Cardoso
Dude, doing this kind of language conversion goes a little outside the scope of the site, there is no unique way to do this, besides, being by desktop application, involve a lot that can make a response too extensive.
– user28595
@diegofm friend, you could have helped with some example in java of uploading any file using some method of your choice. I put the code in my original post.
– Lucas Cardoso