How to call Json Post request with queryparam on client side? - java

I wrote both Service and CLient part of application. I tested my service with "Postman" application and it is working fine with url = http://192.168.2.50:8084/FaceBusinessService/webresources/service/login?phone=123456789&password=1234
However when I try to call it on my Android Application it is not working. While debuging on service side I see that phone and password parameters are NULL.
Here is my service side :
#Path("login")
#POST
#Produces("application/json")
public String postJson(#QueryParam("phone")String phone, #QueryParam("password") String password) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(phone, password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}
Here is my android app side :
private UserInfo loginUser(String phone, String password) {
UserInfo userInfo = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.2.27:8084/FaceBusinessService/webresources/service/login");
try {
/*
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("phone", new StringBody(phone));
entity.addPart("password", new StringBody(password));
post.setEntity(entity);
*/
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("phone", phone));
params.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Log.d(TAG, "POST String: " + post.toString());
try {
HttpResponse response = httpClient.execute(post);
if (response.getEntity().getContentLength() > 0) {
String json_string = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(json_string);
// TODO
return userInfo;
}
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return null;
}
I tried both MultipartEntity and NameValuePair but none of them worked. Could you give me idea how to handle this issue?

Note that when testing with Postman you passed parameters (user name and password) as part of the URL (URL encoded), which can be directly retrieved on the server side. (you don't even need a POST request for this). Your objects are passed as string objects, not JSON objects.
In your client code , the URL is different because you're encoding the parameters as part of the POST request entity (payload). The parameters are packaged inside of the request/message body and not in the URL.
Now since your URL doesn't have the parameters, you should retrieve them by deserializing the request (desderialize the JSON request into a UserInfo object).
Note that you should rewrite your server side code completely as it should accept a application/JSON object but it apparently should return/produce a String object (plain/text or application/HTML).
I'm not familiar with GSON but your code might look something like
#Path("login")
#POST
#Produces("text/plain")
#Consumes("application/json")
public String postJson(UserInfo ui) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(ui.phone, ui.password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}

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.

IBM MF8 Adapter Mashup - POST Requests

I tried a sample for post requests in IBM MF8 Java adapter.
Inside this adapter, I am trying to to call another Java adapter, SampleAdapter and want to do a POST with userDetails as parameter
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/balanced")
#OAuthSecurity(enabled = false)
public JSONObject generate(UserDetails userDetails , HttpRequest request, HttpSession session) throws UnsupportedEncodingException {
String messages = null;
String getProcedureURL = "/SampleAdapter/resource";
StringEntity requestEntity = new StringEntity(userDetails.toString(),ContentType.APPLICATION_JSON);
HttpPost httpPost = new HttpPost(getProcedureURL);
httpPost.setEntity(requestEntity);
JSONObject jsonObj = null;
HttpResponse response;
try {
response = adaptersAPI.executeAdapterRequest(httpPost);
jsonObj = adaptersAPI.getResponseAsJSON(response);
messages = (String)jsonObj.get("subscriptionMessage");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("value", messages);
return json;
}
SampleAdapter has to get the object userDetails. So that I can use it in the back end for some operations.
But, here I am unable to get the data into SampleAdapter. Also, I tried returning some String from SampleAdapter.
I get the below error
{"responseText":"","error":"Response cannot be parsed to JSON"}
I know that IBM MF does the json conversion internally, but here how is it possible to do a POST from one adapter to adapter.
I see samples given only for GET requests.
Any suggestions to do for POST?
I wrote you a short example based on yours:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/balanced")
#OAuthSecurity(enabled = false)
public JSONObject generate() throws UnsupportedEncodingException {
String messages = null;
String getProcedureURL = "/SampleAdapter/resource/hello";
StringEntity requestEntity = new StringEntity("world", ContentType.APPLICATION_JSON);
HttpPost httpPost = new HttpPost(getProcedureURL);
httpPost.setEntity(requestEntity);
JSONObject jsonObj = null;
HttpResponse response;
try {
response = adaptersAPI.executeAdapterRequest(httpPost);
jsonObj = adaptersAPI.getResponseAsJSON(response);
messages = "Hello " + (String)jsonObj.get("name");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("value", messages);
return json;
}
And here is the POST endpoint:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/hello")
#OAuthSecurity(enabled = false)
public Map<String, String> hello(String name) {
Map<String, String> result = new HashMap<String, String>();
result.put("name", name);
return result;
}
I hope this will help you.

Passing JSONArray via Apache httpclient

I am trying to pass an array of objects with several attributes to a php webservice using apache httpclient but I'm not sure how. I have tried to use JSON to encode the array and objects. The below methods create the JSON objects and then add them to a JSONArray:
createArray(){
JSONArray arr = new JSONArray();
}
public void addObj(long var1, int var2, int var3, int var4){
JSONObject obj;
try {
obj = new JSONObject();
obj.put("one:", var1);
obj.put("two:", var2);
obj.put("three:", var3);
obj.put("four:", var4);
arr.put(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
Next I have a class to pass my data to my webservice:
public class Upload {
private String userID = null;
private String password = null;
private String email = null;
Upload(String userID, String password, String email){
this.userID = userID;
this.password = password;
this.email = email;
}
public void uploadData(JSONArray arr) throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.mysite.com")
.setPath("/mypage.php")
.build();
HttpPost httppost = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Email", email));
String encoding = new String(
org.apache.commons.codec.binary.Base64.encodeBase64
(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(userID + ":" + password))
);
httppost.setHeader("Authorization", "Basic " + encoding);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
System.out.println(response);
HttpEntity httpEntity = response.getEntity();
String str = "";
if (httpEntity != null) {
str = EntityUtils.toString(httpEntity);
System.out.println(str);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
I thought I might be able to simply pass the JSONArray as a parameter same as before by doing:
params.add(new BasicNameValuePair("JsonArray", arr));
But this doesn't work since add only seems to accept strings. How can I do it?
JsonObject has a toString method that gives you a string representation of the json object. I don't think you need a JsonArray, but in case you need just put it inside a JSONObject.
The point is HTTP only understands strings.
Another point is, in case your json is large, it is better to upload it rather than passing as a parameter.

HTTPResponse's string from Play is empty

I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.

Android login authentication to remote MySQL database

Here's my java code:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
String res = response.toString();
// res = res.trim();
res = res.replaceAll("\\s+", "");
//error.setText(res);
if (res.equals("1")) {
txtError.setText("Correct Username or Password");
//Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
//startActivity(i);
} else {
txtError.setText("Sorry!! Incorrect Username or Password");
}
} catch (Exception e) {
txtUsername.setText(e.toString());
}
}
});
I thinks there's an error in my res.equals because it keeps saying "Invalid Username or password" even though I've entered the correct username or password. But when I change the res.equals to res.contains it keeps saying "correct username or password" even though i've entered the correct username and password. I really need your help. to all mastered in android development. Hope you could help me on this. And also, when i change the txtError.setText(res) just to check if it returns 1 and 0 it does not.
This needs to be done in the php file not in the Android code:
<?php
define('DB_USER', "root"); //username used to connect to the database.
define('DB_PASSWORD', ""); //password used to connect to the database.
define('DB_DATABASE', "dbname"); //database name
define('DB_SERVER', "127.0.0.1"); //database server address
?>
Using a JSON parser, you would then need to parse the data on the server. You need to use something similar to the following:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//Method to connect to the database
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//The following works just as in normal GET and POST methods
try {
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
In a second class, you would then need to define the connection parameters as follows:
public class UserFunctions {
private JSONParser jsonParser;
private static String loginURL = "http://www.sampleweb.com/login.php";
private static String registerURL = "http://www.sampleweb.com/register.php";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
In addition to this, you would finally need to use your application classes to parse data and show it to the users. There are several online tutorials on how this can be done.
Hope this helps :)
It is really difficult to figure out what is going on with out the response from server. To debug the issue, for both valid and invalid user name/password combinations check the response of http://www.sampleweb.com/imba.php using a POST library like curl or Postman

Categories

Resources