how to make call to jersy post method asynchronously? - java

how to make post call asynchronously (jersy)? I do not want to get any response from this url
public void callAPI(String url,int Id,long se_eln,String reportName String ,String startDate, String endDate){
Map map= new HashMap();
map.put("Id", Id);
map.put("reportName",reportNameString);
map.put("startDate", startDate);
map.put("endDate", endDate);
map.put("accountId", se_eln);
try {
//System.out.println("calling post method");
String str = new ObjectMapper().writeValueAsString(dataMismatchMap);
//
//PostMethod postMethod = new PostMethod(url);
PostMethod postMethod = new PostMethod(url);
RequestEntity requestEntity = new StringRequestEntity(str);
postMethod.setRequestEntity(requestEntity);
postMethod.setRequestHeader("Content-Type", "application/json;charset=utf-8");
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(postMethod);
//System.out.println("result is "+result);
webre
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
how to make post call asynchronously (jersy)? I do not want to get any response from this url

i think there is way to make async calls in apache http client, as i can see you already using it. at simplest you can put request call in simple thread and let let it execute. if i find on making async call through http client will update answer...

This is for get but you can modify to use post replace .rx().get(); by rx().post(...); .
rx.Observable<Response> observable = Rx.newClient(RxObservableInvoker.class)
// .target("http://javaresteasydemo-ravikant.rhcloud.com/rest/hello/getDataNoZip/")
.target("http://jerseyexample-ravikant.rhcloud.com/rest/jws/getDataAsClient")
.register(JacksonFeature.class).request().header("key", "12345").rx().get();
observable.subscribe(new Action1<Response>() {
#Override
public void call(Response response) {
try {
System.out.println(" Inside call ");
// System.out.println(response.readEntity(List.class));
//List<java.util.LinkedHashMap> lst = response.readEntity(List.class);
ObjectMapper ob = new ObjectMapper();
List<User> pojos = ob.convertValue(response.readEntity(List.class), new TypeReference<List<User>>() {
});
for (User user : pojos) {
System.out.println(user.getPost());
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
});

Related

http post request return 400

I'm using HTTP post method to call Gitlab API which in return it gives me 400 response code.
I have tested the gitlab api with postman with providing propers headers and content body as JSON.
it worked fine and. ( I use gitlab create branch api )
I have debugged the application using eclipse and , there is some specific line which gave me null
I'm using apache http client 4.5.5 to handle http requests.
this is my first method to create a branch
public HttpResponse createBranch(String projectId, String branchName, String ref) {
// url is ok, i debugged it
String url = this.API_BASE_URL + projectId + "/repository/branches";
//branchName = "uifix branch";
//ref = "master";
JSONObject obj = new JSONObject();
try {
obj.put("branch", branchName);
obj.put("ref", ref);
} catch (JSONException e) {
e.printStackTrace();
}
Map<String, String> headerParams = new HashMap<String, String>();
headerParams.put("Private-Token", PAT);
headerParams.put("Content-Type", "application/json; utf-8");
headerParams.put("Accept", "application/json");
return HttpUtility.httpPostForResourceCreation(url, headerParams, obj.toString());
}
then will call the following method which is in httputlity class.
public static HttpResponse httpPostForResourceCreation(String url, Map<String, String> headerParam, String body) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body, ContentType.APPLICATION_JSON);
for (Map.Entry<String, String> entry : headerParam.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
request.setEntity(params); // I think problem is here. when I debugged it , it shows null.
return execute(request);
}
then will call the last method
private static HttpResponse execute(HttpRequestBase request) {
HttpClient httpClient = HttpUtility.buildHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(response.getStatusLine().getStatusCode() == 201) {
System.out.println("resource successfully created: " + 201);
} else {
System.out.println("resource creation failed: " + response.getStatusLine().getStatusCode());
}
return response;
}
expected result should be "resource successfully created: + 201"
instead of I'm getting "resource creation failed: 400"
here I attached my request object content
so, what I'm missing here ? Any help would be appreciated.

trying to validate a login from android json post with a status code

I am trying to validate a login using the below code. My challenge is to how get a response of 200 status code and if yes display the welcome screen. This is my code attempt but it has no status to confirm is the post is successful thereafter take the next action.
public void executeLoginValidation() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("email", loginActivityEmail.getText().toString());
comment.put("password", loginActivityPassword.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://localhost:88/API/web/app_dev.php/validatelogin/", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Please how can I modify the above form post code to return a status code and thereafter take the necessary step fron login screen
As the other said before me, try getting the status code from the HttpResponse:
public void executeLoginValidation() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("email", loginActivityEmail.getText().toString());
comment.put("password", loginActivityPassword.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
HttpResponse response = makeRequest("http://localhost:88/API/web/app_dev.php/validatelogin/",json);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
showSplashScreen();
}else{
//ErrorHandling
}
}

Android - HTTP GET on separate thread

Background:
I am new to android programming. I want to simply do an http get request to a local server.
I want to pass this request a name as a parameter and want to get a return in json. This issue that I cannot execute it on the main thread. How can I do this?
Here is what I tried:
main class:
itemsAdapter.add(get.getName(device.getName()));
Seperate class in same file:
private class httpGet extends AsyncTask<Editable, Void, Integer> {
protected String doInBackground(Editable... params) {
Editable editable = params[0];
return getName(editable.toString());
}
final String getName(String btName) {
HttpResponse response = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://192.168.1.105/getName.php?q=" + btName);
request.setURI(website);
response = client.execute(request);
// Convert String to json object
JSONObject json = new JSONObject(response.toString());
// get LL json object
JSONObject json_Name = json.getJSONObject("Name");
// get value from LL Json Object
name = json_Name.getString("value"); //<< get value here
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
// Do something to recover ... or kill the app.
}
return result;
}
protected void onPostExecute(Integer result) {
// here you have the result
}
I am not sure if this is even a good way to do this task. I also have no idea how I would call it.
AsyncTask allows you to perform a background operation in a different thread without manipulating threads/handlers.
It should be this way:
private class httpGet extends AsyncTask<ParamForDoInBackground, ParamForOnProgressUpdate, ParamForOnPostExecute> {
protected Long doInBackground(ParamForDoInBackground... urls) {
// do the request here
}
protected void onProgressUpdate(ParamForOnProgressUpdate progress) {
// if you need to show any progress of the
// request from doInBackground
}
protected void onPostExecute(ParamForOnPostExecute result) {
// this method will run when doInBackground
// is done executing
}
}
Then you can execute an AsyncTask:
new httpGet().execute(ParamForDoInBackground);
You can use the following as a reference: AndroidBackgroundProcessing and Android Developer AsyncTask
You should learn how the asyncTask work. Inside DoInBackground you should to put the code referent to the HTTPRequest. I recommend to use methods to improve the understanding of code. Here is an example of one of my apps:
public String query(String uri) {
HttpClient cliente = new DefaultHttpClient();
HttpContext contexto = new BasicHttpContext();
HttpPost httpPost = new HttpPost(uri);
HttpResponse response = null;
String resultado=null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("dato", cod_restaurante));
httpPost.setEntity(new UrlEncodedFormEntity(params));
response = cliente.execute(httpPost, contexto);
HttpEntity entity = response.getEntity();
resultado = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
}
return resultado;
}
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params)
{
result=query(params[0]);
return result;
}
protected void onPostExecute(final String resultadoDoInBackground)
{
//here put the code to modify the UI
}
}
Then in your activity onCreate() method you execute the Asynktask.
new MyAsyncTask().execute(" ");
You can read more about AsyncTask here:
AsyncTask Android Developer

How to send json from android to php?

To post json from android to php, i used Volley library StringRequest object.
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// some code
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//some code
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
ArrayList<Command> commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND);
String jsonCommands = new Gson().toJson(commands);
params.put("commands", jsonCommands);
return params;
}
};
And to catch the data in php and verify if it was sent correcttly, I used this
echo $_POST["commands"];
Output:
[{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"CF77 COIN FINDER\",\"url_image\":\"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg\",\"name\":\"CF77 COIN FINDER\",\"pid\":12,\"price\":500.0},\"product_quantity\":3},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"JEOSONAR 3D DUAL SYSTEM\",\"url_image\":\"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg\",\"name\":\"JEOSONAR 3D DUAL SYSTEM\",\"pid\":15,\"price\":500.0},\"product_quantity\":1},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"MAKRO POINTER\",\"url_image\":\"IMG_Macro.jpg\",\"name\":\"MAKRO POINTER\",\"pid\":18,\"price\":500.0},\"product_quantity\":3}]
I have noticed that when sending the json string with POST Method using Volley library, a lot of anti-slashes have been added to escape double quotes.
So here comes my problem:
I want to decode json to an array of objects in php, so i used
$commands = json_decode( $_POST["commands"],true);
But it always returns an empty array because of the invalide above json (caused by the anti-slashes).
Is there a method in php or in java SDK providing a contract for sending and receiving json without having this kind of problems? Or should i reformat the json in php and delete all the anti-slashes?
The problem is that you try to send the json data in the URL parameters.
You need to override the getBody() method to return the json data as request body, not as url parameters.
Eg:
/**
* Returns the raw POST or PUT body to be sent.
*
* #throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
return new Gson().toJson(commands).getBytes();
}
And then in PHP you can:
$jsonRequest = json_decode(stream_get_contents(STDIN));
first there is problem with the json itself is not build correctly is better to JSONObject for this, for example:
JSONObject js = new JSONObject();
try {
js.put("value",10);
} catch (JSONException e) {
e.printStackTrace();
}
String jss = js.toString();
you can check if the parse is success by copy the string and copy it in online parser like this http://json.parser.online.fr/
Finally, I solved my problem using a custom json_decode method in order to clean the json string before decoding it.
function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
// search and remove comments like /* */ and //
$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);
// search and remove all backslashes
$json = str_replace("\\","", $json);
if(version_compare(phpversion(), '5.4.0', '>=')) {
$json = json_decode($json, $assoc, $depth, $options);
}
elseif(version_compare(phpversion(), '5.3.0', '>=')) {
$json = json_decode($json, $assoc, $depth);
}
else {
$json = json_decode($json, $assoc);
}
return $json;
}
You can use this method to send json to web service.
public String makeServiceCallSubmit(String url, int method,
JSONArray object) {
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);
httpPost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(object.toString());
// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpResponse = httpClient.execute(httpPost);
}
httpEntity = httpResponse.getEntity();
Response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Response;
}

Android Https OAuth 401 Unauthorized error

private void login() {
androidID = Secure.getString(MainActivity.this.getContentResolver(), Secure.ANDROID_ID);
String uP = androidID.concat(":ClientTrustedSecret");
byte[] authByteAry = null;
try {
authByteAry = uP.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String base64 = Base64.encodeToString(authByteAry, Base64.DEFAULT).trim();
client.addHeader("Authorization", "Basic ".concat(base64));
// Following format is required to post to OAuth
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("grant_type", "password");
jsonObject.put("username", "abc");
jsonObject.put("password", "abc");
} catch (JSONException e1) {
e1.printStackTrace();
}
String contentType = "application/json; charset=UTF-8";
StringEntity data = null;
try {
// Send the json to the server
data = new StringEntity(jsonObject.toString());
client.post(MainActivity.this, baseURL.concat("/tokens"), data, contentType, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
oauthAccessTokenString = jsonObject.get("access_token").toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t, String err) {
System.out.println("login failed");
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
The above is how I login. And when making another web serivce call I get the unauthorized. The unlock method requires the following headers.
http://i.imgur.com/EaWDO.png
private void unlock()
{
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.addHeader("Locale", "en_US");
asyncHttpClient.addHeader("X-Originator-Type", "app");
asyncHttpClient.addHeader("Content-Type", "application/json");
// asyncHttpClient.addHeader("Connection", "Keep-Alive");
// asyncHttpClient.addHeader("X-Device-Id", androidID);
// asyncHttpClient.addHeader("X-via", deviceId);
// asyncHttpClient.addHeader("ClientID", "abc#abc.com");
asyncHttpClient.addHeader("Authorization", "Bearer ".concat(oauthAccessTokenString));
asyncHttpClient.get("host/users?loginName=abc#abc.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
#Override
public void onFailure(Throwable t, String err) {
System.out.println("Unlock server call failed");
Log.d("printing error: ", err);
}
});
}
Above code throws 401 unauthorized exception. No references in documentation which I have, to call back url. I am providing the oauth access token just fine, but then why is it that I still get 401? Does the secret has anything to do with the second call? I am told is that I need to set up my headers that way. I am also told that "For https, the client needs to be able to handle the validation of the certificate. Does anyone knows how to solve it?
It was a wrong web service address :( There was no need to handle the validation of the certificate. There was nothing about call back url. The secret had nothing to do. But the documentation that I have is very poorly written, at one place they mentioned only the headers and then in another place they say body is required is well. So just make sure you go through the documents properly.

Categories

Resources