Post with Robospice and okHttp - post

I perform a POST using Robospice and okHttp :
public String loadDataFromNetwork() throws Exception {
uriBuilder = Uri.parse(url).buildUpon();
uri = new URI(uriBuilder.build().toString());
tmp = "user=" + user + "&password=" + pwd
HttpURLConnection connect = new OkUrlFactory(client).open(uri.toURL());
// Send post request
connect.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connect.getOutputStream());
wr.writeBytes(tmp);
wr.flush();
wr.close();
// Read the response
in = connect.getInputStream();
}
Is there a better way to send a post (with Robospice/okHttp) ?
NB : my code is working fine, just want to know if it's correct or not...

The problem is that if I want to use the okHttp POST like that :
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
with Robospice, RequestBody and newCall and isSuccessful cannot be resolved !
Do I have a solution to use okHttp post WITH Robospice ? (I know how to make a GET, but not a POST...)

Related

Is there any way to bulk delete all permissions of a file using the IGraphServiceClient?

As part of a user action, we are using the MS Graph Java SDK to first list all permissions of a file, then iterating over the list of permissions to delete each one individually. This seems to have some performance issues. We were wondering if there is any way to batch the calls using the IGraphServiceClient.
Relevant APIs used:
https://learn.microsoft.com/en-us/graph/api/driveitem-list-permissions?view=graph-rest-1.0&tabs=http
https://learn.microsoft.com/en-us/graph/api/permission-delete?view=graph-rest-1.0&tabs=http
You can make batch requests.
1. Create MSBatch Request Steps (examples below)
Request requestGetMe = new Request.Builder().url("https://graph.microsoft.com/v1.0/me/").build();
List<String> arrayOfDependsOnIdsGetMe = null;
MSBatchRequestStep stepGetMe = new MSBatchRequestStep("1", requestGetMe, arrayOfDependsOnIdsGetMe);
Request requestGetMePlannerTasks = new Request.Builder().url("https://graph.microsoft.com/v1.0/me/planner/tasks").build();
List<String> arrayOfDependsOnIdsGetMePlannerTasks = Arrays.asList("1");
MSBatchRequestStep stepMePlannerTasks = new MSBatchRequestStep("2", requestGetMePlannerTasks, arrayOfDependsOnIdsGetMePlannerTasks);
String body = "{" +
"\"displayName\": \"My Notebook\"" +
"}";
RequestBody postBody = RequestBody.create(MediaType.parse("application/json"), body);
Request requestCreateNotebook = new Request
.Builder()
.addHeader("Content-Type", "application/json")
.url("https://graph.microsoft.com/v1.0/me/onenote/notebooks")
.post(postBody)
.build();
MSBatchRequestStep stepCreateNotebook = new MSBatchRequestStep("3", requestCreateNotebook, Arrays.asList("2"));
2. Create MSBatch Request Content and get content
List<MSBatchRequestStep> steps = Arrays.asList(stepGetMe, stepMePlannerTasks, stepCreateNotebook);
MSBatchRequestContent requestContent = new MSBatchRequestContent(steps);
String content = requestContent.getBatchRequestContent();
3. Make call to $batch endpoint
OkHttpClient client = HttpClients.createDefault(auth);
Request batchRequest = new Request
.Builder()
.url("https://graph.microsoft.com/v1.0/$batch")
.post(RequestBody.create(MediaType.parse("application/json"), content))
.build();
Response batchResponse = client.newCall(batchRequest).execute();
4. Create MSBatch Response Content
MSBatchResponseContent responseContent = new MSBatchResponseContent(batchResponse);
Response responseGetMe = responseContent.getResponseById("1");
// Use the response of each request

HTTP response code: 411 for LinkedIn with ApacheOltu

Looking at the https://developer.linkedin.com/docs/oauth2 I try here to get an access token.
What can be wrong with this piece of code ?
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
TokenRequestBuilder r = OAuthClientRequest
.tokenLocation("https://www.linkedin.com/oauth/v2/accessToken")
.setCode(code)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(LinkedInClientID)
.setClientSecret(LinkedInClientSecret)
.setRedirectURI("http://localhost:8080/authenticatedLinkedIn");
Map<String,String> m = new HashMap<String,String>();
m.put("Content-Type", "application/x-www-form-urlencoded");
int bodyLength = r.buildBodyMessage().getBody().length();
System.out.println("Body l = " + bodyLength);
m.put("Content-Length", Integer.toString(bodyLength));
r.buildHeaderMessage().setHeaders(m);
OAuthClientRequest request = r.buildQueryMessage();
OAuthJSONAccessTokenResponse tk = oAuthClient.accessToken(request, OAuth.HttpMethod.POST);
I get the following error :
Server returned HTTP response code: 411 for URL:
https://www.linkedin.com/oauth/v2/accessToken?code=AQSZfSXpQ6z3575474fhfbZmxJQofGiwtpw53Y1FnlALvKBWJgQKfJH8kvHM-3f5ZtOqndit594S2cmZrFuiNaXcBOHuSf8yMgFgr4uh-a40Ag&grant_type=authorization_code&client_secret=gHPiGTTyb1KKHPEP&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FauthenticatedLinkedIn&client_id=86txkd469mat
You need to send a POST request with params in body urlenconded... so
First change:
OAuthClientRequest request = r.buildQueryMessage();
With:
OAuthClientRequest request = r.buildBodyMessage();
Then you do not need to put any header Oltu will manage this for U.
Hope it will help.

HttpClient POST request to https

I'm working on a WinRT app that does login to a webpage and get some data. The problem is that I'm getting a "HttpRequestException: An error occurred while sending the request" message. Here is the code:
Uri url = new Uri("https://miyoigo-b.yoigo.com/selfcare/login");
HttpContent msg = new StringContent("account[cli]=" + number + "&password=" + pass);
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
handler.UseCookies = true;
handler.CookieContainer = new CookieContainer();
HttpClient req = new HttpClient(handler);
req.DefaultRequestHeaders.Add("Host", "miyoigo-b.yoigo.com");
req.DefaultRequestHeaders.ExpectContinue = false;
HttpResponseMessage response = await req.PostAsync(url, msg);
string responseBody = await response.Content.ReadAsStringAsync();
I've been trying a lot of thing I found over the internet, even disabling my firewall, but nothing worked. I'm porting this from a Windows Phone app and it did work with this:
Uri url = new Uri("https://miyoigo-b.yoigo.com/selfcare/login");
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.Headers["Host"] = "miyoigo-b.yoigo.com";
req.CookieContainer = new CookieContainer();
req.BeginGetRequestStream(new AsyncCallback(WriteCallback), req);
And afterwards, in the Callback I created a Stream and wrote the credentials.
Any idea?? I know that the problem is only with this webpage, maybe I'm forgetting to send something or the format of the POST content is not correct...
Thanks
Finally the problema was that Win8 Metro Apps only accepts SSL3.1 and this webpage was using SSL3.0. The solution was using the new version of the webpage.
Thank you all

Oauth not working CX api

I'm trying to use the oauth for CX exposed api, I followed their documentation, still I'm getting HTTP "BAD REQUEST" error, Here is the code -
String method = "POST";
String code = "";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", code),
new NameValuePair("redirect_uri",URLEncoder.encode(CALLBACK_URL, "UTF-8"))
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
httpClient.executeMethod(httpMethod);
Thanks,
Hemant
I've tested the following slight modification of your code and it works. You might double check that
Your key has been approved (this shouldn't be the problem given the
error you are seeing).
You are using the correct ACCESS_TOKEN_ENDPOINT_URL
Try having the redirect_uri be the same for both the auth_code response and the token request
String method = "POST";
String authCode = "[AUTH-CODE-HERE]";
String CONSUMER_KEY="[YOUR-KEY-HERE]";
String CONSUMER_SECRET="[YOUR-SECRET-HERE]";
String ACCESS_TOKEN_ENDPOINT_URL="https://api.cx.com/1/oauth/token";
String REDIRECT_URI="[YOUR-REDIRECT-HERE]";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", authCode),
new NameValuePair("redirect_uri", REDIRECT_URI)
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
int responseCode = httpClient.executeMethod(httpMethod);
System.out.println(responseCode);
System.out.println(httpMethod.getResponseBodyAsString());
If you are still running into issues, can you post the result of the following line: System.out.println(httpMethod.getResponseBodyAsString());
The CX developer API has been discontinued.
Sorry for the inconvenience.

Google Places API: Adding a new Place: Java/Groovy

Can't get the POST working? What's wrong?
Note: This works for a GET with autocomplete
GET works without signing the url
I'm following the Web services steps to Sign the URL with my "API Key"
Docs say"client id" still?
http://code.google.com/apis/maps/documentation/webservices/
2.Try sending the POST data with the signed URL (tried the unsigned signature aswell)
def signedUrl = "https://maps.googleapis.com/maps/api/place/add/json?key=xxxxxkeyxxxxxx&sensor=false&signature=xxxxxxxxxxsignaturexxxxxx"
String postData = "{'location': { 'lat': '-33.8669710','lng': '151.1958750'},'accuracy': '50','name': 'Google Shoes!'}"
URL urlPost = new URL(signedUrl);
URLConnection connection = urlPost.openConnection();
connection.addRequestProperty("Referer", "http://www.mysite.com");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("CONTENT-TYPE", "text/json");
connection.setRequestProperty("CONTENT-LENGTH", postData.length() + "");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(postData);
out.close();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
println json
Returns a 403
"java.io.IOException: Server returned HTTP response code: 403 for URL:"
Simular to the "Java Access"section under they give an example of a GET
http://code.google.com/apis/websearch/docs/#fonje
Ok solved.
No signing the URL required
postData string was wrong
should have been
String postData = "{\"location\": { \"lat\": -33.8669710,\"lng\": 151.1958750},\"accuracy\": 50,\"name\": \"Google Shoes!\", \"types\":[\"bar\"]}"

Resources