Twitter:send direct message using scribe - android

Here is my code to send send direct message using scribe. But it gives me null response. What am I doing wrong?
OAuthRequest req;
OAuthService s;
s = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(APIKEY)
.apiSecret(APISECRET)
.callback(CALLBACK)
.build();
req = new OAuthRequest(Verb.POST, "https://api.twitter.com/1/direct_messages/new.format?user_id="+user_id+"&text=my app test");
s.signRequest(MyTwitteraccesToken, req);
Response response = req.send();
if (response.getBody() != null) {
String t=response.getBody();
Log.w("twittersent","twittersent"+t);
}
Can anybody help me ?

Try specifying the format as XML or JSON in your request URL. Also, make sure your entire text file is URL encoded.

Related

Spring Rest : Handling POST requests, at server end

I am asking this question based on the answers in this link
POST request via RestTemplate in JSON
I actually wanted to send JSON from client and receive the same at REST server. Since the client part is done in the link I mentioned above. For the same how would I handle that request at server end.
CLIENT:
// create request body
JSONObject request = new JSONObject();
request.put("username", name);
request.put("password", password);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> loginResponse = restTemplate
.exchange(urlString, HttpMethod.POST, entity, String.class);
if (loginResponse.getStatusCode() == HttpStatus.OK) {
JSONObject userJson = new JSONObject(loginResponse.getBody());
} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {
// nono... bad credentials
}
SERVER:
#RequestMapping(method=RequestMethod.POST, value = "/login")
public ResponseEntity<String> login(#RequestBody HttpEntity<String> entity) {
JSONObject jsonObject = new JSONObject(entity.getBody());
String username = jsonObject.getString("username");
return new ResponseEntity<>(username, HttpStatus.OK);
}
This gives me 400 bad request error at client side. Hoping for some clues about how to handle this at server side.
HTTPEntity should not be used in your server method. Instead use the argument which is being passed to HTTPEntity from your client. In your case it has to String since you are passing string from client. Below code should work for you.
#RequestMapping(method=RequestMethod.POST, value = "/login")
public ResponseEntity<String> login(#RequestBody String jsonStr) {
System.out.println("jsonStr " + jsonStr);
JSONObject jsonObject = new JSONObject(jsonStr);
String username = jsonObject.getString("username");
return new ResponseEntity<String>(username, HttpStatus.OK);
}
My advice is to create bean class and use it in server and client instead of converting it to String. It will improve readability of the code.
When using the Spring RestTemplate, I usually prefer to exchange objects directly. For example:
Step 1: Declare and define a data holder class
class User {
private String username;
private String password;
... accessor methods, constructors, etc. ...
}
Step 2: Send objects of this class to the server using RestTemplate
... You have a RestTemplate instance to send data to the server ...
// You have an object to send to the server, such as:
User user = new User("user", "secret");
// Set HTTP headers for an error-free exchange with the server.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Generate an HTTP request payload.
HttpEntity<User> request = new HttpEntity<User>(user, headers);
// Send the payload to the server.
restTemplate.exchange("[url]", [HttpMethod], request, User.class);
Step 3: Configure a ContentNegotiatingViewResolver on the server
Declare a bean of the type ContentNegotiatingViewResolver in the Spring XML or Java configuration. This will help the server automatically bind HTTP requests with bean objects.
Step 4: Receive the request on the server
#RestController
#RequestMapping("/user")
class UserAPI {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public User create(User user) {
// Process the user.
// Possibly return the same user, although anything can be returned.
return user;
}
}
The ContentNegotiatingViewResolver ensures that the incoming request gets translated into a User instance without any other intervention.
Step 5: Receive the response on the client
// Receive the response.
HttpEntity<User> response = restTemplate.exchange("[url]", [HttpMethod], request, User.class);
// Unwrap the object from the response.
user = response.getBody();
You will notice that the client and the server both use the same bean class (User). This keeps both in sync as any breaking change in the bean structure would immediately cause a compilation failure for one or both, necessitating a fix before the code is deployed.

Correct syntax for adding parameters to get() and post() request using okhttp in Android

What I want to achieve ?
I am trying to send two parameters in my Server URL using OkHttp through both get and post bcoz i want to know the syntax for both the methods.
What I had Tried ?
I have searched SO for questions on OkHttp but those had not solved my IllegalArgumentException.
I have seen below links :
Add query params to a GET request in okhttp in Android
and this
How to add parameters to api (http post) using okhttp library in Android
and
How to add query parameters to a HTTP GET request by OkHttp?
Exception from code 2:
Code I had used till now :
1)GET
urls = chain.request().httpUrl() <-- NullPointerException Line
.newBuilder()
.scheme("http")
.host(SERVER_IP)
.addQueryParameter("from", valueFrom)
.addQueryParameter("to",valueTo)
.build();
request = chain.request().newBuilder().url(urls).build();
response = chain.proceed(request);
2)GET
urls =new HttpUrl.Builder()
.host(SERVER_IP) <--- IllegalArgumentException line
.addQueryParameter("from", valueFrom)
.addQueryParameter("to", valueTo)
.build();
request = new Request.Builder().url(urls).build();
response = client.newCall(request).execute();
3)POST
body = new
MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("from",
valueFrom).addFormDataPart("to",valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
4)POST
body = new FormEncodingBuilder().add("from", valueFrom).add("to",
valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
build.gradle
dependencies
{
compile files('libs/okhttp-2.5.0.jar')
compile files('libs/okio-1.6.0.jar')
}
Thanks In Advance...
Edit :
The above code for POST request is working fine now
But for GET request I still have no solution.
Just set your GET parameter extend your URL:
RequestBody body = new FormEncodingBuilder()
.add("requestParamName", requestParameter.getRequestParams())
.build();
Request request = new Request.Builder()
.url("https://www.test.com/serviceTest?parama=abc&paramb=123")
.post(body)
.build();

Add parameter into body with Scribe Library

I'm developing an Android app and I have integrated Scribe library to make http connection with OAuth1.0 with Magento. My problem is that I need to send a request with a parameter into body but without a key. Now I make login correctly and I have my Token authorized, I get products from server, categories, blah blah... but I cannot make checkout because always I get code "401 Authorization require". I think that the problem could be by the parameter in the body.
My code:
...
#Override
protected String doInBackground(String... json) {
String result = null;
org.scribe.model.Response response = null;
String url = Global.BASE_URL + "cart/1";
if(Global.TOKEN_AUTHORIZED != null) {
OAuthRequest request = new OAuthRequest(Verb.POST, url);
//I only need insert a json into body without key
request.addBodyParameter(<I don't need a key>, json[0]);
Global.OAUTH_SERVICE.signRequest(Global.TOKEN_AUTHORIZED, request);
response = request.send();
}
if(response != null && response.getCode() == 200) {
result = response.getBody();
} else {
result = "ERROR";
}
return result;
}
...
How I put only a parameter in the body but without key, value?
Thanks in advance :)
I found the solution:
First is necessary to add a Header to say that content of the request is a json
To add a single parameter into the body without key, value exists a method called addPayload(String)
Now I get a response with code 200 :)
if(Global.TOKEN_AUTHORIZED != null) {
OAuthRequest request = new OAuthRequest(Verb.POST, url);
request.addHeader("Content-Type", "application/json");
request.addPayload(params[0]);
Global.OAUTH_SERVICE.signRequest(Global.TOKEN_AUTHORIZED, request);
response = request.send();
}
I hope to help somebody :)

post json as httpcontent to webapi

I have a webapi that i want to post json to and then return json. Im using xamarin to create my android app but it doesn't seem to support PostAsJsonAsync method for the httpclient. So im now trying PostAsync method that post httpcontent. So what i want to do is convert my json to so that it is of format httpcontent and json so that i can post it to my webapi. This is my code:
var clientRequest = new ResourceByNameRequest
{
Name = "G60",
UserId = "1"
};
var param = JsonConvert.SerializeObject(clientRequest);
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
var client = new HttpClient();
var cancellationToken = new CancellationToken();
var result = client.PostAsync("https://mctwebapi-test.entrematic.com/api/Resource/ResourceByName?", content, cancellationToken).Result;
return reslist;
this just runs till the timeout. I can't figure out why it doesn't work. If you have any other suggestions on how to post json to webapi using Xamarin im more than happy to try that out!
Plz help!

How to send a POST request with JSON data using google api client library for java?

I'm trying to send a post request using the google api client library but not able to succeed.
This is the snippet I'm using
UrlEncodedContent urlEncodedContent = new UrlEncodedContent(paramMap); //paramMap contains email and password keypairs
HttpRequest request = httpRequestFactory.buildPostRequest(new GenericUrl(Constants.PHP_SERVICE_BASE_PATH + mPath) , urlEncodedContent);
String response = request.execute().parseAsString();
I do not get the expected response. I think it is because the post parameters i.e email and password are not being sent in the correct format. I need to send them in JSON.
NOTE : I'm not using the library for a google web service.
I'm using a Map as input of the JSON. The map is input for the JsonHttpContent used by the post request.
Map<String, String> json = new HashMap<String, String>();
json.put("lat", Double.toString(location.getLatitude()));
json.put("lng", Double.toString(location.getLongitude()));
final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);
final HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(url), content);
UrlEncodedContent is used for posting HTTP form content (Content-Type: application/x-www-form-urlencoded). If the Content-Type is application/json you should probably use
http://code.google.com/p/google-http-java-client/source/browse/google-http-client/src/main/java/com/google/api/client/http/json/JsonHttpContent.java

Categories

Resources