Last active
December 27, 2015 11:59
-
-
Save cirocosta/7322530 to your computer and use it in GitHub Desktop.
PostDataNotAsync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("¶m" + 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