EDIT 2
Found my error i was passing invalid an invalid parameter just remebered i was tryiong out stuff.
Sorry For the Trouble GUYS
I am using Google custom search engine for the first time and so far every thing is fine. However, when i try to send a query for an item which has a white space the search engine returns a bad request response eg
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ q.replace(" ", "%20") + "&searchType=" + searchType
+ "&imgType=" + imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
This returns this
com.google.api.client.http.HttpResponseException: 400 Bad Request
EDIT
i took the advice of 323go and tried encoding my q and this is how i implemented it
String encodedParms = null;
try {
encodedParms = URLEncoder.encode(q, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ encodedParms + "&searchType=" + searchType + "&imgType="
+ imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
Log.d(Tag, myUrl);
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request;
try {
request = httpRequestFactory.buildGetRequest(new GenericUrl(myUrl));
String response = streamToString(request.execute().getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In my log i got this as the url
https://www.googleapis.com/customsearch/v1?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-w&cx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Sunway+Lagoon+Theme+Park&searchType=image&imgType=photo&imgSize=xxlarge&num=20&alt=json
i still got the same bad request error
please can anyone tell me what i am doing worng
Why dont you add "+" between words, I had same issue
With "word1 word2" - response 400 - Bad request
With "word1+word2" - response 2000 - Bad request
Related
I have String Json:
String data = "param:"+"{\"dataFile\": \n" +
"{\"user\": \"asdasdasd\", \n" +
"\"pwd\":\"vasdadsda\", \"email\": \"vasdasdasd#gg.com\" \n" +
"}\n" +
"}";
Then try to send post to API with webview JSON like this:
myWebView.postUrl("url.com", data.getBytes());
from API the json process with "param" key then get the value, but the json get from API is null, any clue ?
I post my data like this. You may also try with this.
String postData = null;
try {
postData = "email=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.EMAIL), "UTF-8") + "&password=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.PASSWORD), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
webview.postUrl("url.com",postData.getBytes());
I'm having a encoding issue when I send a AJAX request to an API Endpoint.
I have this Endpoint in the code below using Java Spring:
#Autowired
ApiKeyRepository apiKeyRepository;
#RequestMapping(value= "/weather/{cityName}/{fuCity}/now", method = {RequestMethod.GET}, produces="application/json" )
public ResponseEntity<Weather> getWeatherNowByCityName(#PathVariable(value = "cityName") String cityName, #PathVariable(value = "fuCity") State fuCity) throws JSONException, ParseException, java.text.ParseException {
String newCityName = cityName.toLowerCase();
try {
newCityName = URLDecoder.decode(newCityName , "UTF-8").replace(" ", "%20");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String weatherEndpoint = "/api/v1/locale/city?name=" + newCityName + "&state=" + fuCity.toString();
String appToken = apiKeyRepository.getByservice("climaTempo");
URL weatherDomain = new URL("http://apiadvisor.climatempo.com.br" + weatherEndpoint + "&token=" + appToken);
/// From here I send a JSON Request to the 'weatherDomain' to get the Weather from the city and her state that I get from the EndPoint Parameters
}
And I send this jQuery Ajax request to the Endpoint:
var uf = $("#colWeather #selectState").val();
var city = $("#colWeather #selectCity").val();
$.ajax({
url: host + '/weather/' + city + '/' + uf + '/now',
type: 'GET',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
async: true
}).done(function (JSONReturn) {
//Actions with JSONReturn
});
But here in Brazil we have some cities with accents and cedilla like "Avaí" from "SP", "Mairiporã" from "SP" and "Missão Velha" from "CE".
If I send to the Endpoint an URL like "/weather/Americana/SP/now" or "/weather/Piracicaba/SP/now" the Endpoint gets the JSON return without problems.
But if I send to the Endpoint an URL like "/weather/Mairiporã/SP/now" or "/weather/Avaí/SP/now" the ClimaTempo API returns a null JSON and I get a NullPointerException.
I'm thinking that is a problem with the accents, but I can't send just "/weather/Mairipora/SP/now" without the accents because the ClimaTempo API demands that the city name must go with the accents, otherwise it returns a null JSON...
What am I doing wrong?
You need to encode and decode your characters.
Encode in JavaScript
Instead of url: host + '/weather/' + city + '/' + uf + '/now', go for
url: host + '/weather/' + encodeURIComponent(city) + '/' + uf + '/now'
Decode in Java
Instead of String newCityName = cityName.toLowerCase();, go for
String newCityName = URLDecoder.decode(cityName, Charsets.UTF_8.name()).toLowerCase();
Hey guys!
I'm currently trying to create an app that uses the Twitter API to get timelines of users. I'm currently stuck at a specific point! My user has already logged in and I've already received the access token and the token secret. I'm now trying to send a get request to the Twitter server.
My problem is that I'm always getting a 400 bad request error code WITHOUT any kind of message.
I'm using Volley to send the requests - Heres the code
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Response Time: " + error.getNetworkTimeMs() + " ms");
Log.e(TAG, "Code: " + error.networkResponse.statusCode);
Log.e(TAG, "Data: " + new String(error.networkResponse.data));
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Long tsLong = System.currentTimeMillis() / 1000;
//I receive all the difference parts
String consumerKey = context.getString(R.string.twitter_consumer_key);
String nonce = GenerationHelper.generateNonce();
String signature_method = "HMAC-SHA1";
String timestamp = tsLong.toString();
String token = sTwitterToken;
String version = "1.0";
// I use this list to pass the parameters to the function
// generating the signature
List<String> param= new ArrayList<>();
param.add("screen_name=" + username);
param.add("count=" + count);
param.add("oauth_token" + sTwitterToken);
param.add("oauth_consumer_key=" + consumerKey);
param.add("oauth_nonce=" + nonce);
param.add("oauth_signature_method=" + signature_method);
param.add("oauth_timestamp=" + timestamp);
param.add("oauth_version=" + version);
String signature = GenerationHelper.generateSignature(context, param, "POST", "https://api.twitter.com/1.1/statuses/user_timeline.json");
// I create the header String
StringBuilder paramBuilder = new StringBuilder();
paramBuilder.append("oauth_consumer_key=\"" + consumerKey + "\", ");
paramBuilder.append("oauth_nonce=\"" + nonce + "\", ");
paramBuilder.append("oauth_signature=\"" + signature + "\", ");
paramBuilder.append("oauth_signature_method=\"" + "HMAC-SHA1" + "\", ");
paramBuilder.append("oauth_timestamp=\"" + timestamp + "\", ");
paramBuilder.append("oauth_token=\"" + sTwitterToken + "\", ");
paramBuilder.append("oauth_version=\"" + "1.0" + "\"");
String credentialString = paramBuilder.toString();
Log.d(TAG, credentialString);
params.put("Authorization", "OAuth " + credentialString);
return params;
}
};
My current response is
Code: 400
Data:
If I remove the line adding the authorization data I get the response
Code: 400
Data: {"errors":[{"code":215,"message":"Bad Authentication data."}]}
I'm pretty sure that I don't get rate limited because I'm just sending about 10 requests per 15 minutes.
Does anybody have any idea why I'm having this problem?
String pay= "["
+ "{"
+ "\"internalAssessmentResponseId\" : \"Mer\\/ccclsv__AC1B752E-D079-4BA9-AA4F-46E1F8DDC11F__3048\","
+ "\"responses\":["
+ "{"
+ "\"assessmentCreatedDate\":\"2016-11-25T11:35:54\","
+ "\"responseData\":[],"
+ "\"assessmentId\":\"943\","
+ "}"
+ "],"
+ "\"addtionalInformation\":[],"
+ "\"emailId\":\"lucky#me.com\","
+ "\"salesTeam\" :\"\","
+ "\"demographic\": {"
+ "},"
+ "\"repId\":\"AJMA-OG9OMQ\","
+ "\"assesseeId\":\"AGHA-2D0FVL\","
+ "\"assesseeType\":\"CONTACT\","
+ "\"typeOfResponse\":\"iPad\","
+ "\"userTimeZone\":\"a\""
+ "}"
+ "]";
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod("http://signature");
post.setRequestEntity(new StringRequestEntity(pay, "application/json", null));
httpclient.executeMethod(post);
String jsonResponse = post.getResponseBodyAsString();
jsonInsertRes = jsonResponse;
System.out.println("Response in create==>"+jsonResponse);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch
(IOException e)
{
e.printStackTrace();
}
return jsonString.toString();
}
I am getting wrong response like this
Can not construct instance of org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput, problem: abstract types can only be instantiated with additional type information
at [Source: org.apache.catalina.connector.CoyoteInputStream#11ff00b3; line: 1, column: 1]
You can try sending JSON string as a string form parameter
and then on server read the JSON string value and convert the string to a Java Object(say object of Message.java as for example).
Message msgFromJSON = new ObjectMapper().readValue(JSONString, Message.class);
I have tried few times and it worked fine.
I'm coding a webservice in Java using aws and in many method i need to have a try catch block that can actually log any errors that can occur in the execution of each exposed methods.
#WebMethod(operationName = "listingBucket")
public String listingBucket() {
String message = "";
try {
message = "Listing buckets";
for (Bucket bucket : s3.listBuckets()) {
message += " - " + bucket.getName();
}
} catch (AmazonServiceException ase) {
message += "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
} catch (AmazonClientException ace) {
message += "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
}
return message;
}
#WebMethod(operationName = "addObjectToBucket")
public String addObjectToBucket(String bucketName, String objectName, File file) throws IOException{
if ( file == null ){
file = createSampleFile();
}
String message = "";
try {
message += "Uploading a new object to S3 from a file\n";
s3.putObject(new PutObjectRequest(bucketName, objectName, file));
} catch (AmazonServiceException ase) {
message += "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
} catch (AmazonClientException ace) {
message += "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
}
return message;
}
How Can i avoid to repeat this try catch block throw all methods that use this kind of stuff ?
Thanks for your help !
Edit : Actually I modified the code :
private String parseError(AmazonServiceException ase) {
String message;
message = "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
return message;
}
private String parseError(AmazonClientException ace) {
String message;
message += "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
return message;
}
#WebMethod(operationName = "listingBucket")
public String listingBucket() {
String message = "";
try {
message = "Listing buckets";
for (Bucket bucket : s3.listBuckets()) {
message += " - " + bucket.getName();
}
} catch (AmazonServiceException exc) {
message += parseError(exc);
} catch (AmazonClientException exc) {
message += parseError(exc);
}
return message;
}
Clearer indeed ! :)
I'll just take a look about the command pattern to see if I can use it for this kind of application.
There are two aspects in here.
One thing is about the code repetition in the catch block; which can be easily turned into something like
public class ExceptionHandler {
public String buildMessageFor(AmazonServiceException ase) {
... }
public String buildMessageFor(AmazonClientException ase) {
... }
...
You can even unit test that thing very easily (where "naming" could be improved; but I guess the example should be good enough to get you going).
That would also make it easier in the future to turn from "pure string" messages into something else. You know, hardcoding user messages in source code is not the smartest thing to do.
The other part, the try/catch itself; somehow depends. You see, the try/catch is an essential part of your operations; so many people would argue that you simply keep that structure in your code. The only alternative would be to define some kind of interface like
public interface RunAmazonOperation {
public void run() throws Amazon...
}
Then you can write down all your operations as little classes implementing that interface; to be called by some framework that does the try/catch for you. If that is worth the price ... depends on your application.
In other words: if you turn to the "command" pattern; you might find it useful to define a variety of "commands"; implementing that interface; thus reducing the number of places with try/catch dramatically.
Just do it with methods. One possibility would look like:
String parseError(AmazonServiceException ase){
String message;
message = "Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.";
message += "Error Message: " + ase.getMessage();
message += "HTTP Status Code: " + ase.getStatusCode();
message += "AWS Error Code: " + ase.getErrorCode();
message += "Error Type: " + ase.getErrorType();
message += "Request ID: " + ase.getRequestId();
return message;
}
String parseError(AmazonClientException ace){
String message;
message = "Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.";
message += "Error Message: " + ace.getMessage();
return message;
}
Now you can just write:
catch(AmazonServiceException exc){
message=parseError(exc);
}
catch(AmazonClientException exc){
message=parseError(exc);
}