Spring Basic OAuth throwing bad Request Exception - android

Hi i am trying to connect with elastic search using Spring resttemplate but it gives exception saying bad request. below is my code
String plainCreds = "elasticsearch:*****";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + base64Creds);
final String url = "https://ff92ba95318093026b7a06180f2b2d19.us-east-1.aws.found.io:9243/jinkjobposts_dev_v1/jobPosts";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<String> request = new HttpEntity<>( headers);
Log.d("location", "before exchange");
ResponseEntity<JobPosts> response = restTemplate.exchange(url, HttpMethod.POST, request, JobPosts.class);
JobPosts jobPosts = response.getBody();
Log.d("location", "after exchange");
list = Arrays.asList(jobPosts);
it gives this exception.
FATAL EXCEPTION: AsyncTask #2
Process: in.thoughtsmith.jink, PID: 8902
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1115)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:590)
at java.lang.Thread.run(Thread.java:818)
Caused by: org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:76)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:524)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:481)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:415)
at in.thoughtsmith.jink.MapsActivity$SearchJob.doInBackground(MapsActivity.java:690)
at in.thoughtsmith.jink.MapsActivity$SearchJob.doInBackground(MapsActivity.java:645)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1115) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:590) 
at java.lang.Thread.run(Thread.java:818) 
Please me i am doing this for the first time

It's not an authorization issue. Your url is simply missing the _search endpoint at the end, hence the error HTTP 400 you're getting.
final String url = "https://ff92ba95318093026b7a06180f2b2d19.us-east-1.aws.found.io:9243/jinkjobposts_dev_v1/jobPosts/_search";

Related

AsyncTask DoInBackground downloading Google Spreadsheets Data Returning Null?

Here is the code:
#Override
public String doInBackground(String... params)
{
try
{
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //Cast HttpUrlConnection because URL does not contain methods available to url, creates object
httpURLConnection.setRequestMethod("GET"); //Request data from source
httpURLConnection.setDoInput(true);
httpURLConnection.connect(); //Object actually connects, connect() invoked by getInputStream() etc.
//Reads data from network stream
InputStream inputStream = httpURLConnection.getInputStream();
//Rather than read one character at a time from the network or disk, BufferedReader reads a larger block at a time
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Used to create mutable string e.g. append()
StringBuilder stringBuilder = new StringBuilder();
String line = "";
//Change stream data to StringBuilder data
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
I'm basically downloading the JSON data from Google Spreadsheets, but the result returned from the doInBackground function continues to return some sort of a null object reference. What does this mean?...
EDIT*
Here is my logcat:
07-28 12:41:30.289 3796-3891/com.example.steven.app E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.steven.app, PID: 3796
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.AlertDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:95)
at com.example.steven.database.DownloadGS.doInBackground(DownloadGS.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
Picture of what is actually being stored inside String result...
My problem was:
URL url = new URL("http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
I found out that by reading here:
URLConnection Doesn't Follow Redirect
the setFollowRedirect and setInstanceFollowRedirects only work automatically when the redirected protocol is same . ie from http to http and https to https. (Shalvika)
I changed the statement to:
URL url = new URL("https://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH");
Your code looks fine, the problem is that you are not allowed to get data from that URL.
On hitting this URL "http://spreadsheets.google.com/tq?key=BLAHBLOAHBLAH"
I am getting following response, so i guess you are getting access denied from server.
google.visualization.Query.setResponse (
{
"version": "0.6",
"status": "error",
"errors": [
{
"reason": "access_denied",
"message": "Access denied",
"detailed_message": "Access denied"
}]
}
)

Error in adding file to MultipartEntityBuilder in android

In my Android project I'm using MultipartEntityBuilder in uploading files to backend using an AsyncTask. I'm using httpmime-4.5.2 in my project.my doInBackground method in uploading AsyncTask is as below.
#Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
entity.addPart("file", fileBody);
HttpEntity entity_ = entity.build();
httpPost.setEntity(entity_);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
but when the AsyncTask is executing it gives me following error.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1912)
at com.marpak.livefarmerpro.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddMonitors.java:1884)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
 
so whats wrong with this code. how can I fix this. Thanks and regards.
Finally I figured out the reason. I've imported httpmime library in to the project. But in my case it need another library to be executed together with httpmime. I import httpcore library and build the project. it solve the problem. :D I just add below line to build.gradle and re build the project.
compile 'org.apache.httpcomponents:httpcore:4.4.4'

File upload using MultipartEntityBuilder gives an Error

In my android app I'm using AsyncTask to upload a file to the backend. In there I use MultipartEntityBuilder in my doInBackground method. my doInBackground part is as follows,
#Override
protected String doInBackground(String... params) {
try {
String serverLoaction = params[0];
String filePath = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(serverLoaction);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(filePath));
StringBody stringBody = new StringBody("data", ContentType.MULTIPART_FORM_DATA);
builder.addPart("file", fileBody);
builder.addPart("name", stringBody);
httpPost.setEntity(builder.build());
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in downloading image", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
This show me no syntax errors. but when I run the code an exception throws and the app stops. the error log is as below.
Process: com.x.x, PID: 6271
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NoSuchFieldError: org.apache.http.message.BasicHeaderValueFormatter.INSTANCE
at org.apache.http.entity.ContentType.toString(ContentType.java:153)
at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:56)
at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
at org.apache.http.entity.mime.MultipartEntityBuilder.build(MultipartEntityBuilder.java:240)
at com.x.x.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddCropMonitors.java:1905)
at com.x.x.ui.farm_activity.AddCropMonitors$UploadFileTask.doInBackground(AddCropMonitors.java:1875)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:841)
 
it tells NoSuchFieldError exception raises, but I go through several tutorials and it's seems to me the code is ok according to them. the line number points to where the error occurs is points to
httpPost.setEntity(builder.build());
line. so whats the problem with this code segment and how can I fix this. thanks and regards!
I think this is due to library which you are using in your build.gradle file.
Please check with below code once
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
add this in your build.gradle file.
implementation 'org.apache.httpcomponents:httpmime:4.5.10'

java.lang.NullPointerException at HttpGet httpGet = new HttpGet(url);

public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
This is the class i use for getting String from REST request
12-26 10:51:35.610 1750-1778/hackerspace.invento.ebooks E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: hackerspace.invento.ebooks, PID: 1750
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at java.net.URI.parseURI(URI.java:353)
at java.net.URI.<init>(URI.java:204)
at java.net.URI.create(URI.java:725)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at hackerspace.invento.ebooks.ServiceHandler.makeServiceCall(ServiceHandler.java:63)
at hackerspace.invento.ebooks.ServiceHandler.makeServiceCall(ServiceHandler.java:39)
at hackerspace.invento.ebooks.Books$GetResult.doInBackground(Books.java:113)
at hackerspace.invento.ebooks.Books$GetResult.doInBackground(Books.java:94)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
and this is the Log Error i get How do i solve this?
My guess would be that you are either passing a NULL string into your method, or for some reason the string is getting set to NULL if the HttpGet() method fails to resolve the URL or something else goes wrong. Try appending this at the end of your try / catch statement:
catch (Exception e)
{
Log.e("MyApp", "exception: " + e.getMessage());
Log.e("MyApp", "exception: " + e.toString());
}
Normally, a statement such as this is poor practice to use in your software, as it will essentially squash any exception you get without allowing you to handle the various exception cases. However, for debugging purposes, adding this statement at the end of you try/catch statement will allow you to see if there is perhaps an exception that you are missing that is causing the HttpGet() method to fail which, in turn, causes your NULL error. If you do detect another exception, you can handle it appropriately so that your method no longer returns a NULL string.
Your url is NULL
URISyntaxException
Throws: java.lang.NullPointerException If either the input or reason strings are null

Force Close asynctask (Illegal Character)

I am getting this error, which is odd because it works from another activity calling the same async task. I can not figure out what the illegal character is in my query:
09-06 17:42:29.098 32101-32497/com.beerportfolio.beerportfoliopro E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 50: http://beerportfolio.com/app_getTopTaste.php?t=Rum
at java.net.URI.create(URI.java:727)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.readJSONFeed(GetTopTasteBeersJSON.java:139)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.doInBackground(GetTopTasteBeersJSON.java:49)
at com.example.beerportfoliopro.GetTopTasteBeersJSON.doInBackground(GetTopTasteBeersJSON.java:34)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 5 more
Illegal character in query at index 50: http://beerportfolio.com/app_getTopTaste.php?t=Rum
It's the character at index 50, which is right after "Rum". It's probably some sort of whitespace character. You'll have to post your code for how you get/generate that URL if you want more details, but you might need to add some code to strip whitespace somewhere.
try to trim the string. It removes unwanted whitespace at the end of the string.
String url = " http://beerportfolio.com/app_getTopTaste.php?t=Rum";
HttpGet request = new HttpGet(url.trim());
Try the below
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String url = " http://beerportfolio.com/app_getTopTaste.php?t=Rum";
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i(".......",_response);
I just tried your url and i do get the response
09-06 22:05:04.547: I/.......(1460): [{"beer":"Rum Cask","rate":"5","id":"dkRDyR","breweryID":"jC0TAa"}]
As kabuko stated character 50 is after Rum. I think kabuko is right.
I guess you have space at the end of url. It is better to encode the url as below.
String query = URLEncoder.encode("Rum ", "utf-8");
String url = "http://beerportfolio.com/app_getTopTaste.php?t=" + query;
HttpGet request = new HttpGet(url);
URL encoding in Android

Categories

Resources