I tried the following way
public class GoogleOAuth2 {
String authURL = "https://accounts.google.com/o/oauth2/auth";
String tokenURL = "https://oauth2.googleapis.com/token";
public void execute() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(tokenURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("client_id",
"*********"));
params.add(new BasicNameValuePair("client_secret", "*****"));
params.add(new BasicNameValuePair("grant_type", "Authorization Code"));
params.add(new BasicNameValuePair("redirect_url", "https://localhost:8080"));
params.add(new BasicNameValuePair("scope", "https://www.googleapis.com/auth/cloud-platform"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(post);
String body = EntityUtils.toString(response.getEntity());
System.out.println(body);
} catch (Exception ex) {
System.out.println("Catched an error in Authenticating user : " + ex.getMessage());
}
}}
Now, this shows this error ,
(I have tried grant-type as Code,password,offline also)
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: Authorization Code"
}
What m i missing?
Can you please guide me to the right direction? I have Tried using Postman and i was able to get an access Token from here.
Related
I would like to authorize my server to access to application-specific data on the Google Drive of my client. Therefore I need to use OAuth 2.0 for Web Server Applications. I followed the tutorial provided by Google. However I failed to pass step 5 (exchange an authorization code for an access token). Everytime I get: Error 400 Bad Request.
I tried to see if the code that was passed in my request expired. However, as I use my code directly when I get it, it doesn't seem to be the issue. I also checked if my redirect_uri was authorized in the Google Console for this client id.
#GET
#Path("get-oauth-google-drive/{email}/{token}")
#Produces(MediaType.TEXT_PLAIN)
public String getOauthGoogleDrive(
#PathParam("email") String email,
#PathParam("token") String token
) {
String linkForOauth = "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=" + client_id + "&redirect_uri=" + domain + "/rest/myresource/callback&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline";
return linkForOauth;
}
#POST
#Consumes({MediaType.APPLICATION_JSON})
#Path("granted-callback")
#Produces(MediaType.TEXT_PLAIN)
public String callbackGranted(
String msg
) {
System.out.println("Drive Access GRANTED");
return "";
}
#GET
#Path("callback")
#Produces(MediaType.TEXT_PLAIN)
public String callbackOauth(
#QueryParam("code") String code,
#QueryParam("scope") String scope
) {
try
{
HttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://www.googleapis.com/oauth2/v4/token");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
InputStream inputStream = getResourceAsStream(CREDENTIALS_FILE_PATH);
GoogleClientSecrets googleClientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(inputStream));
String clientId = googleClientSecrets.getDetails().getClientId();
String clientSecret = googleClientSecrets.getDetails().getClientSecret();
String redirectURI = domain + "/rest/myresource/granted-callback";
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("code", code));
params.add(new BasicNameValuePair("client_id", clientId));
params.add(new BasicNameValuePair("client_secret", clientSecret));
params.add(new BasicNameValuePair("redirect_uri", URLEncoder.encode(redirectURI, "UTF-8")));
params.add(new BasicNameValuePair("grant_type", "authorization_code"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
System.out.println(response);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return "Merci de votre inscription vous allez être redirigé incessamment sous peu.";
}
Steps 1, 2, 3 and 4 are working fine but step 5 is always writing Error 400 Bad Request. Thanks for your help !
I'm sending parameters from my android app to the backend and trying to retrieve the parameters sent by my android clients in my POST Method but I keep getting null parameters even though the clients are sending parameters which are not null.
Java POST Method:
#POST
#Produces({ "application/json" })
#Path("/login")
public LoginResponse Login(#FormParam("email") String email, #FormParam("password") String password) {
LoginResponse response = new LoginResponse();
if(email != null && password != null && email.length() != 0 && password.length() != 0){
//Detect if null or empty
//Code
}
return response;
}
Android Client:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY_APP_NAME.appspot.com/user/login");
String json = "";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("email", "roger#gmail.com");
jsonObject.accumulate("password", "123");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httppost.setEntity(se);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("ACCEPT", "application/json");
HttpResponse httpResponse = httpclient.execute(httppost);
}
catch(Exception ex) { }
I believe the Content-Type of the method and the client is the same as well. Why am I not receiving the parameters from the Java Backend Method?
CHECKED:
The URL is correct and the connection is working
The Parameters sent by the app are not null
We hope i got you, try NameValuePair
public void postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/yourscript.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("string", "Hey"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// Catch Protocol Exception
} catch (IOException e) {
// Catch IOException
}
}
Just in case you have similar problems, I'd suggest using Fiddler
which is a free http inspector and debugger by which you can see the http request your app is sending to the backend server and the backend answer.
Best of luck
for example,grab full content from https://play.google.com/store/apps
I found it posts data:
"start=15&num=5&numChildren=10pagTok=CA8QDxjh2ND3psHQ4pcB%3AS%3AANO1ljLBy5U&ipf=1&xhr=1"
to show next browser page
then I used
HttpPost httpPost = new HttpPost("https://play.google.com/store/apps");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("start","15"));
params.add(new BasicNameValuePair("num","5"));
params.add(new BasicNameValuePair("numChildren","10"));
params.add(new BasicNameValuePair("pagTok","CA8QDxjh2ND3psHQ4pcB"));
params.add(new BasicNameValuePair("ipf","1"));
params.add(new BasicNameValuePair("xhr","1"));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
CloseableHttpResponse response = getSSLHttpClient().execute(httpPost);
HttpEntity entity = response.getEntity();
try {
if(entity != null) {
return EntityUtils.toString(entity);
}
} finally {
EntityUtils.consume(entity);
response.close();
}
but in the end I can't get the web document from googleplay,the result is some javascript,
what's wrong?
Apache HTTP Client is used to get the page content. If you need to execute javascript on this page you can use HtmlUnit.
Here is an example
i'am tring to login into website with post method ... to right here the code is code but the response always give me 200 ... i want to know if i logged in successfully with the right username and password or not !!! ... also if i removed permitAll() it give me networkonmainthreadexception
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
private void sendPost() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://svuonline.org/isis/login.php?");
String user=username.getText().toString();
String pass=password.getText().toString();
String fpage="/isis/index.php";
/* if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}*/
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_name", user));
nameValuePairs.add(new BasicNameValuePair("user_pass", pass));
nameValuePairs.add(new BasicNameValuePair("user_otp", null));
nameValuePairs.add(new BasicNameValuePair("from_page", fpage));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String Rcode=response.toString();
Toast.makeText(getBaseContext(), Rcode+"", Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(getBaseContext(), e+"", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getBaseContext(), e+"", Toast.LENGTH_LONG).show();
}
}
You can read about it here:
HTTP response
10.2.1 200 OK
The request has succeeded.
I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
The XML Response that i will be getting is
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username#company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair.
An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.
to #BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
Here is an example of convertStramToString.
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Try HttpClient for Java:
http://hc.apache.org/httpclient-3.x/
You can reuse the implementation I added to ACRA:
http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application).
I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!