I am using httpcomponents-client-4.2.5-bin for the ClientFormSubmit. I used the example to login to facebook using Oauth. My Oauth login has following steps
first login to facebook using
https://www.facebook.com/dialog/oauth?client_id=xxxxxxx&redirect_uri=http://localhost:8080/
give the login details it redirects to the local host and have code parameter in url
I need to get that code value.
Code is
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://www.facebook.com/dialog/oauth?client_id=358300034293206&redirect_uri=http://localhost:8080/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://www.facebook.com/dialog/oauth?client_id=358300034293206&redirect_uri=http://localhost:8080/");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "*****"));
nvps.add(new BasicNameValuePair("pass", "*****"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Double check we've got right page " + EntityUtils.toString(entity));
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
httpclient.getConnectionManager().shutdown();
}catch(Exception e)
{
System.out.println( "Something bad just happened." );
System.out.println( e );
e.printStackTrace();
}
}
Is it possible to get the redirect url using request header? Thanks In Advance.
Using HttpClient 4.3 APIs
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
HttpGet httpGet = new HttpGet("http://www.google.com/");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet, context);
try {
System.out.println("Response status: " + httpResponse.getStatusLine());
System.out.println("Last request URI: " + context.getRequest().getRequestLine());
URICollection redirectLocations = context.getRedirectLocations();
if (redirectLocations != null) {
System.out.println("All intermediate redirects: " + redirectLocations.getAll());
}
EntityUtils.consume(httpResponse.getEntity());
} finally {
httpResponse.close();
}
Using HttpClient 4.2 APIs
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext context = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.google.com/");
try {
HttpResponse httpResponse = httpClient.execute(httpGet, context);
System.out.println("Response status: " + httpResponse.getStatusLine());
HttpRequest req = (HttpRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
System.out.println("Last request URI: " + req.getRequestLine());
RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
DefaultRedirectStrategy.REDIRECT_LOCATIONS);
if (redirectLocations != null) {
System.out.println("All intermediate redirects: " + redirectLocations.getAll());
}
EntityUtils.consume(httpResponse.getEntity());
} finally {
httpGet.releaseConnection();
}
Related
authenticate_user method intended to create it to get the list of projects through the REST API in java:
#GET
#Path("/projects")
#Produces({MediaType.APPLICATION_JSON})
public boolean authenticate_user(String username, String password)
{
boolean status = false;
boolean isUser = isUserExists(username, password);
if (isUser)
{
HttpResponse response = clientConfig(username, password, "projects");
System.out.println("ProjectResponse >>>" + response);
HttpEntity entity = response.getEntity();
String content=null;
try
{
content = EntityUtils.toString(entity);
}
catch (ParseException | IOException e)
{
e.printStackTrace();
}
System.out.println("ResponseContent><><><"+content);
System.out.println("ContentMimeType: "+EntityUtils.getContentMimeType(entity));
if (response != null)
{
JSONArray getArray =new JSONArray();//Projects
status=true;
System.out.println("SuccessFully login");
}else
{
// TODO user is not validated
System.out.println("Error: Not Authenticated");
status = false;
}
} return status;
}
ClientConfiguration class:
public HttpResponse clientConfig(String username, String password, String prms)
{
try
{
HttpClient httpclient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://" + _HOST + "/" + prms);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("Type", "Basic Auth"));
nvps.add(new BasicNameValuePair("Username", username));
nvps.add(new BasicNameValuePair("Password", password));
httpget.setHeader("Authorization", "Basic " + new UrlEncodedFormEntity(nvps));
// Execute and get the response.
httpget.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpget, httpContext);
response.setHeader("Content-Type", "application/json");
if (response.getStatusLine().getStatusCode() != 200)
{
throw new IOException("Non-successful HTTP response: " + response.getStatusLine().getStatusCode() + ":"
+ response.getStatusLine().getReasonPhrase());
}
else if (response.getStatusLine().getStatusCode() == 200)
{
System.out.println("Response>>>" + response);
System.out.println("HTTPResponse: " + response.getStatusLine().getStatusCode() + ":"
+ response.getStatusLine().getReasonPhrase());
flag = true;
return response;
}
else
{
System.out.println("Status is not 200");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
And my output is html response instead of html response I need the JSON format, Its return me login page
HTTPResponse: 200:OK
<!DOCTYPE html>
<html lang="en">
................ </html>
ContentMimeType: text/html
SuccessFully login
Any one help me to find out the problem.
Try like this:
String json_string = EntityUtils.toString(response.getEntity());
JSONArray jsonArr = new JSONArray(json_string);
Thank you, Friends, Now I solved this issue with Jersey framework. And here is a solution of it.
String url = "http://support.sigmastream.com/issues.json";
String output = "";
String authString = username + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
try
{
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc).get(ClientResponse.class);
if (resp.getStatus() != 200)
{
throw new IOException(
"Non-successful HTTP response: " + resp.getStatus() + " : " + resp.getStatusInfo());
}
else
{
output = resp.getEntity(String.class);
System.out.println("response: " + output);
}
}
catch (IOException ie)
{
System.out.println(ie.getMessage());
}
I'm using Httpclient-4.5.2.jar and httpcore-4.4.4.jar HttpClient components and I'm getting below error.
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:966)
My source code as follows.
try {
System.out.println("came to try catch");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://bizz.mobilezz.lk/apicall/loanprepaidapi/v1");
StringEntity params =new StringEntity("{\"mobile\":\"776037285\",\"path\":\"IVV\",\"loanAmount\":\"200000\"}");
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", "Bearer casmk34233mlacscmaacsac");
request.addHeader("Accept", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println("response is :"+response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
Please assist me to get rid of this error. I'm trying to send request in post method and get json response.
I found an answer to my question and posting for your reference.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://bizz.mobilezz.lk/apicall/loanprepaidapi/v1");
JSONObject json = new JSONObject();
StringEntity params = new StringEntity("{\"msisdn\":\"" + mobile
+ "\",\"channel\":\"SDD\"}");
new StringEntity(json.toString());
post.addHeader("Host", "mife.dialog.lk");
post.addHeader("content-type", "application/json");
post.addHeader("Authorization", "Bearer " + access_token);
post.addHeader("Accept", "application/json");
// System.out.println("status code is:" + status);
post.setEntity(params);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
System.out.println("status code is :" + status);
resCode = Integer.toString(status);
if (status != 401) {
if (status != 409) {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
String response1 = readAll(rd);
System.out.println(response1);
JSONObject obj = new JSONObject(response1);
resCode = obj.getString("resCode");
resDesc = obj.getString("resDesc");
System.out.println(resCode);
System.out.println(resDesc);
}
}
System.out.println("reason code is :" + resCode);
i have a standard HttpServlet in my java web project. I use Netbeans. I want to call a Restfull Web service inside servlet and after i will catch the response like a JSON and populate a JSP.
I tried to find on the net but i didn't find anything.
Thank you
Here's an example of HttpPost:
try {
HttpPost httpPost = new HttpPost("https://exampleurl/providerexample/api/v1/loansforexample"
);
StringEntity params;
params = new StringEntity("{"
+ "\"clientId\": \"" + "2" + "\","
+ "\"productId\": \"" + "1" + "\","
+ "\"locale\": \"" + "en" + "\"}");
httpPost.addHeader("Content-Type", "text/html"); //or text/plain
httpPost.addHeader("Accept-Encoding", "gzip, deflate, sdch");
httpPost.setEntity(params);
HttpResponse response = client.execute(httpPost);
int statuscode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
if (statuscode == 200) {
System.out.println(responseBody);
}
if (statuscode != 200) {
System.out.println(responseBody);
// JSONObject obj = new JSONObject(responseBody);
// JSONArray errors = obj.getJSONArray("errors");
// String errorMessage = "";
// if (errors.length() > 0) {
// errorMessage = errors.getJSONObject(0).getString("developerMessage");
}
}
catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
HttpGet is pretty much the same.
I try upload some string to server. When I try upload on server, in string:
HttpResponse response = httpclient.execute(httppost);
I have error org.apache.http.client.ClientProtocolException. All code:
public void sendString(String stringToSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(serverAddress);
InputStreamEntity reqEntity = new InputStreamEntity( new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length());
reqEntity.setContentType("application/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
Log.i("SEND", "not send "+response.getStatusLine());
}else{
Log.i("SEND", "send ok "+response.getStatusLine());
}
} catch (IOException e) {
Log.w("IOException", e.toString() +" "+ e.getMessage());
}
}
This should work
public void sendString(String stringToSend) {
try {
HttpParams httpParams=new BasicHttpParams();
DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(serverAddress);
InputStreamEntity reqEntity = new InputStreamEntity( new ByteArrayInputStream(stringToSend.getBytes()), stringToSend.length());
reqEntity.setContentType("application/xml");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != org.apache.http.HttpStatus.SC_OK) {
Log.i("SEND", "not send "+response.getStatusLine());
}else{
Log.i("SEND", "send ok "+response.getStatusLine());
}
} catch (IOException e) {
Log.w("IOException", e.toString() +" "+ e.getMessage());
}
}
I want to login to a site using HttpClient and after logging in I want to search for something and retrieve the contents of the search result.
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class TestHttpClient {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://projecteuler.net/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("http://projecteuler.net/index.php?section=login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
System.out.println("Response "+response.toString());
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str ="";
while ((str = br.readLine()) != null){
System.out.println(""+str);
}
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
httpclient.getConnectionManager().shutdown();
}
}
when I print the output from HttpEntity it's printing the login page contents. How do I get the contents of the page after I login using HttpClient?
The post should mimick the form submit. No need to get the login page first.
If I take a look at http://projecteuler.net, it seems the form is posted to index.php, so I'd try changing the post url:
HttpPost httpost = new HttpPost("http://projecteuler.net/index.php");
Use something like Fire bug to see what is exactly happening in the browser. Maybe you should follow a redirect after logging in (HttpClient supports this).
There also seems to be a parameter called "login"with value "Login" that is being posted.