I have been trying to look for cURL requests for Android Studio, specifically for this type of request in particular:
curl -d "grant_type=client&client_id=123&client_secret=456" https://api.someapp.com/v2/oauth2/token
I have been looking for solutions around the site, but the only closest answer to exist is:
CURL in android
This doesn't solve my issue of the -d command (the link solves for -u), as well as the need for customizable headers (link gives only :, rather than &).
Any help is appreciated!
Just figured it out, never mind guys!
POST with data:
try {
HttpClient client = new DefaultHttpClient();
String postURL = "https://api.someapp.com/v2/oauth2/token";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type","client"));
params.add(new BasicNameValuePair("client_id","123"));
params.add(new BasicNameValuePair("client_secret","456"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
// Successful results
Log.i("Results", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I'm trying to retrieve JSon information for a server that is protected and is redirected to the login page everytime that is trying to get a protected resource. So I should use cookies to implement the access to the information.
Unfortunately POST for each URL(in total 3)that I have, is just working once.
To log in the app is made using the function below:
// Making HTTP request
try {
httpClient = getNewHttpClient();
String redirectedUrl = getUrl(url);
// defaultHttpClient
HttpPost httpPost = new HttpPost(redirectedUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", login));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpContext = new BasicHttpContext();
CookieStore mCookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
if ((html != null) && html.contains("error loginError")) {
} else
return html;
} catch (IOException e) {
}
And after the log in I'm trying to get the information in the same way, but it's just working once per URL. I don't know why, below is how I'm trying to get the information after login.
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
When I'm trying to get the information second time the IOException is throwed, the httpClient and httpContext are both global and static.
I got a solution, I don't think that is a good solution, but it is working at all.
To make it stops to get the IOException, I just made a call to the login function before all post, which means that for all POSTs I have to set a new HTTPContext logged and valid.
If somebody has a better solution I would be pleasure to hear it from you.
PS.: Actually the problem was about the session duration on server side, now it's working properly, anyway I'll let the topic here because could be useful to somebody that is implementing this kind of solution.
I'm working on an android app which uses webview and what I'm trying to accomplish is to successfully pass a base64 encoded image on my php file by using post.Url() and then display it on html5 canvas.
I have no difficulty in my php file (web) my problem is with this:
String url = "http://localhost/folder/postImage.php";
String encodedImage = iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==";
String postData = "image=data:image/png;base64," + encodedImage;
webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));
So, basically that's how my coding works, what I need is to retain the value of postData and not encode it to BASE64 again since it is already encoded in BASE64.
Instead of this :
webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));
What should i put in here:
webview.postUrl(url,EncodingUtils.getBytes(postData, "???????"));
Hope you'll help me with my problem or at least suggest. THANK YOU! :)
HTTP.UTF_8
I run it through http post base 64 and php.
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.mywebsite.com/foo.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("image", image_str));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
I want to use an external website http://www.siirretytnumerot.fi/ in my android application. This website takes in two values PREFIX and NUMBER. I am confused at the moment as I seem not to be getting any output in my textview. I dont know what to use whether httpget or httppost. I tried both and still no result. But when i go to the link for explorer and enter an input the website line changes to http://www.siirretytnumerot.fi/QueryServlet. I have tried to use both still no output.
Please can someone help me look through the website and suggest which of the http methods is correct for me to use?
here is the code I used.
TextView tv=(TextView)findViewById(R.id.display);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.siirretytnumerot.fi/";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("PREFIX", "044"));
params.add(new BasicNameValuePair("NUMBER", "9782231"));
params.add(new BasicNameValuePair("LANGUAGE", "Finnish"));
params.add(new BasicNameValuePair("Submit", "Hae"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
tv.setText(EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
the output from the link comes out as an image source
<img src="QueryServlet?ID=-7187780920186056107&STRING=5WQAy%2BQCUZRGIUJ8qZtpSrmkiKzWp8HRL7Ti1xmFSxMAEZE7GHEtaylOApMGd9qoesY7Pl%2BUN1Z6Kzap9RIg%2Bw==" />
Now how do i read this?
Use developer tools of browser to find out which fields are required.
You should make POST request to http://www.siirretytnumerot.fi/QueryServlet
Try to add these fields to your request:
Submit: Hae
LANGUAGE: Finnish
I hope it'll help
EDIT
It will look like that
TextView tv=(TextView)findViewById(R.id.display);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.siirretytnumerot.fi/";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("PREFIX", "044"));
params.add(new BasicNameValuePair("NUMBER", "9782231"));
//here the new lines
params.add(new BasicNameValuePair("LANGUAGE", "Finnish"));
params.add(new BasicNameValuePair("Submit", "Hae"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
tv.setText(EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
You can view the source and there is a line
<input type="hidden" name="LANGUAGE" value="Finnish">
So you need to add that field too,as they might be using it.So
params.add(new BasicNameValuePair("LANGUAGE", "Finnish"));
I'm currently trying to send data via POST to a server, and the server is handling the data and appends it to a JSON file. I'm currently getting a 422 error and I've been receiving it for a while now. My question is: How do I receive that JSON error itself in Java so that I can see what the error is. All I'm seeing is a HttpResponseException and it doesn't give me anything else. Thanks for the time and help in advance.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mPath);
// Add your data
try
{
List nameValuePairs = new ArrayList(4);
httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
nameValuePairs.add(new BasicNameValuePair("state", "CA"));
nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);
//int status = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.v(TAG, "response: " + responseBody);
//JSONObject response = new JSONObject(responseBody);
int f = 0;
}
catch(HttpResponseException e)
{
Log.e(TAG, e.getLocalizedMessage());
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
you may send your parameters more conveniently by using predefined Json class as below:
String jsonParam = null;
try{
JSONObject param = new JSONObject();
param.put("state", "CA");
param.put("city", "AndDev is Cool!");
//and so on with other parameters
jsonParam = param.toString();
}
catch (Exception e) {
// TODO: handle exception
}
and set the post entity as:
if(jsonParam != null)
httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));
422 error says: Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors
You got a problem with UrlEncodedFormEntity
i am currently working on one application..
in that application i have to use get and post both methods..
get method works properly but in post method suddenly i get the response like
"invalid method.post required"..
my code for that is:
String list_url = "************************";
try {
String appand = TimeStampForAuth.TimeStameMethod(main.this);
String auth = android.util.Base64.encodeToString(("iphone" + ":" +
"2a5a262d5a")
.getBytes("UTF-8"), android.util.Base64.NO_WRAP);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(list_url+appand);
Log.d("URL_LIST", list_url+appand);
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("login",Login));
nvps.add(new BasicNameValuePair("password",password));
nvps.add(new BasicNameValuePair("title",title));
nvps.add(new BasicNameValuePair("category_id",cat_id));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.addHeader("Authorization", "Basic " + auth);
post.setEntity(p_entity);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
String s = EntityUtils.toString(responseEntity);
Log.d("List response", s);
}
catch(Exception e){
System.out.println(e.toString());
}
in that i am missing somethinf or what that i dont know..is all that thing is valid for post method....
please help me as early as possible...
thanking you.........
Try using setHeader() instead of addHeader()
You could try HttpClient 4.1 for Android: http://code.google.com/p/httpclientandroidlib/
(There are bugs in the HttpClient version 4.0 which Android uses.)
You can also debug with it a little more with httpClient.log.enableDebug(true);
If you don't want to use an external library, I'd start debugging the network traffic.
With a software called Wireshark you can see and inspect all Http Requests/Responses very
easily.
For authorization I personally would use:
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(hostname, port),
new UsernamePasswordCredentials(user, pass));
use this instead:
HttpURLConnection connection = (HttpsURLConnection) serviceURL.openConnection();
connection.setRequestMethod("POST");