Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Last active December 27, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cirocosta/7322530 to your computer and use it in GitHub Desktop.
Save cirocosta/7322530 to your computer and use it in GitHub Desktop.
PostDataNotAsync
public class PostDataNotASync {
/* THIS MUST NOT BE USED IN THE MAIN THREAD */
private ArrayList<String> data;
private String endereco;
public PostDataNotASync(String endereco, ArrayList<String> data) {
this.data = data;
this.endereco = endereco;
}
public String sendData() throws Exception {
try {
URL url = new URL(endereco);
StringBuffer param = new StringBuffer();
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
param.append("param" + String.valueOf(i) + "=");
} else {
param.append("&param" + String.valueOf(i) + "=");
}
param.append(URLEncoder.encode(data.get(i), "UTF-8"));
}
String params = param.toString();
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment