HTTP post 400 bad request - android

When I try to use my restTemplate.postForEntity I get a 404 bad request
What is my fault?
Code:
Servercaller:
public ServerError login(String username, String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
String URL = "http://"+ipAddress+"/ProjectTeamF-1.0/service/login.json";
Object[] params = new Object[]{URL,user};
new login().execute(params);
} catch (ResourceAccessException rae) {
receivedUser = null;
return ServerError.ServerNotFound;
} catch (HttpServerErrorException hsee) {
receivedUser = null;
return ServerError.WrongData;
} catch(RestClientException rce){
receivedUser = null;
return ServerError.WrongData;
} catch (Exception e) {
System.out.println("error " + e);
receivedUser = null;
return ServerError.OtherError;
}
return ServerError.NoError;
}
AsyncTask:
public class login extends AsyncTask<Object[], Void, Void> {
public ServerCaller sc = ServerCaller.getInstance();
public User body;
#Override
protected Void doInBackground(Object[]... params) {
String message = "";
try {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> _entity = new HttpEntity<User>((User)params[0][1], requestHeaders);
RestTemplate templ = new RestTemplate();
templ.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
templ.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
ResponseEntity<User> _response = templ.postForEntity(params[0][0].toString(), _entity, User.class); //null here in order there wasn't http converter errors because response type String and [text/html] for JSON are not compatible;
body = _response.getBody();
return null;
} catch (Exception e) {
message = e.getMessage();
return null;
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
sc.setReceivedUser(body);
}
}
When I debug the program crashes at templ.postForEntity(). The error tells me that this is a 400 - bad request.
Thanks!

Related

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

Null Response from Microsoft Emotion Apis

I am always getting response string "[]" in return when using Microsoft Cognitive services Emotion APIs, whenever i send the image obtaining through front-camera in android.
When i checked it with the sample image it gives the required result(Emotion analysis).
I don't know what's the problem with front camera image.
public void AnalyzeImage(final Bitmap bitmap) {
AsyncTask<InputStream, String, String> asyncTask = new AsyncTask<InputStream, String, String>() {
#Override
protected String doInBackground(InputStream... params) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
Map<String, Object> mapParams = new HashMap<>();
String path = serviceHost + "/recognize";
String uri = getUrl(path, mapParams);
mapParams.clear();
byte[] data = output.toByteArray();
mapParams.put("data", data);
String json="";
try {
json = (String) webInvoke("POST", uri, mapParams, "application/octet-stream", false);
Log.d("RESPONSE", json);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... progress) {
}
#Override
protected void onPostExecute(String result) {
tvImageEmotion.setText(result);
}
}.execute();
}
public static String getUrl(String path, Map<String, Object> params) {
StringBuffer url = new StringBuffer(path);
boolean start = true;
for (Map.Entry<String, Object> param : params.entrySet()) {
if (start) {
url.append("?");
start = false;
} else {
url.append("&");
}
try {
url.append(param.getKey() + "=" + URLEncoder.encode(param.getValue().toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return url.toString();
}
private Object webInvoke(String method, String url, Map<String, Object> data, String contentType, boolean responseInputStream) throws Exception, Exception {
HttpPost request = null;
request = new HttpPost(url);
boolean isStream = false;
if (contentType != null && !contentType.isEmpty()) {
request.setHeader("Content-Type", contentType);
if (contentType.toLowerCase().contains("octet-stream")) {
isStream = true;
}
} else {
request.setHeader("Content-Type", "application/json");
}
request.setHeader(headerKey, "0e843fb762464d82ae6f486bad99f629");
try {
request.setEntity(new ByteArrayEntity((byte[]) data.get("data")));
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
if (!responseInputStream) {
return readInput(response.getEntity().getContent());
} else {
return response.getEntity().getContent();
}
} else {
throw new Exception("Error executing POST request! Received error code: " + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
I just found the solution to the problem, actually the image clicked through Camera is rotated to 90 degree, that's why Emotion API was unable to detect any face in the image.When I corrected the image rotation it works perfectly.

Asyntask not executing onPostExecute()

This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.

Access token validation from Google, Google+ Sign-in Android

I want to fetch an access-token from Google and then send it to my server as a JSON object*.
On server I want to validate the access token and then store essential user information.
My server is written in Node.js. How to do that?
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected. Yay!");
findViewById(R.id.sign_in_button).setVisibility(View.INVISIBLE);
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String code;
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"http://schemas.google.com/AddActivity");
String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME;
try {
code = GoogleAuthUtil.getToken(
AuthenticationActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (UserRecoverableAuthException e) {
// Recover
code = null;
//System.out.println(e.printStackTrace());
AuthenticationActivity.this.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (Exception e) {
throw new RuntimeException();
}
return code;
}
#Override
protected void onPostExecute(String token) {
/* if(token!=null)
{
Log.i(TAG, "Access token retrieved:" + token);
//SharedPreference = getApplicationContext().getSharedPreferences("TokenPreference", 0);
//editor = SharedPreference.edit();
editor.putString("access_token",token);
editor.commit();
} */
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://gumbox1.cloudapp.net:3000");
JSONObject data = new JSONObject();
data.put("data", token);
HttpEntity entity = new StringEntity(data.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.execute(post).getEntity().getContent()));
String response = reader.readLine();
Log.e("response", response);
}
catch(Exception e)
{ Log.e("",e.toString());
}
}
};
task.execute();
}
You need to pass auth token to https://www.googleapis.com/oauth2/v1/userinfo?access_token= url. It will return the JSON data for user information.
You should do like
private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
URL url = new URL(USER_INFO_URL + code);
con = (HttpURLConnection) url.openConnection();
InputStream is = con.getInputStream();
// Now convert into String and then into Json

AsyncTask - onPostExecute is not called

I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?

Categories

Resources