Hello Droids..!
Here I come with another demo for HttpClient, in which you have to do login to URL.
The core is used “HttpPost”,
Here is the code,
</pre>
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class Login {
public String HttpClient(String UserName,String Password){
String response;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(your URL); //without parameters
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("api", "Login"));// If you get an error then and then active this line
nameValuePairs.add(new BasicNameValuePair("username", UserName));
nameValuePairs.add(new BasicNameValuePair("password", Password));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(postMethod,resonseHandler);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
How to use:
//Create an object Login login = new Login(); String resp = login.HttpClient(abc,pqr); //here abc -> UserName, pqr -> passwordDownload here:: Login.java
Comments will be appreciated.
![]()
