May 17, 2014

HttpsURLConnection POST example with NameValuePair and UrlEncodedFormEntity

try {
 String u = "https://...";
 
 // Add your data
 List nameValuePairs = new ArrayList(2);
 nameValuePairs.add(new BasicNameValuePair("id", "1"));
 // ...
 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
 
 URL url = new URL(u);
 HttpsURLConnection request = (HttpsURLConnection) url.openConnection();

 request.setUseCaches(false);
 request.setDoOutput(true);
 request.setDoInput(true);

 request.setRequestMethod("POST");
 OutputStream post = request.getOutputStream();
 entity.writeTo(post);
 post.flush();

 BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
 String inputLine, response = "";
 while ((inputLine = in.readLine()) != null) {
  response += inputLine;
 }
 post.close();
 in.close();
} catch (Exception e) {
 Log.e("Your app", "error", e);
}

2 comments:

AmN said...

Hey ! I want to be able to log into Blackboard of my University using HttpsURLConnection. I stumbled across this piece of code and it's giving me a lot of hope since this one doesn't make my app crash.

However nothing gets executed after line: OutputStream post = .... ;
I don't even know if that one gets executed :s Any ideas ?

Unknown said...

You musn't run your code into main function, you can use async or a thread

Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {

String u = "https://...";

// Add your data
List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair("id", "1"));
// ...
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);

URL url = new URL(u);
HttpsURLConnection request = (HttpsURLConnection) url.openConnection();

request.setUseCaches(false);
request.setDoOutput(true);
request.setDoInput(true);

request.setRequestMethod("POST");
OutputStream post = request.getOutputStream();
entity.writeTo(post);
post.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
String inputLine, response = "";
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
post.close();
in.close();
} catch (Exception e) {
Log.e("Your app", "error", e);
}
}
});