Passing JSONArray via Apache httpclient - java

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.

Related

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

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;
}

Login 404 Parse.com REST API Java

We decided to build our own twitter login for aesthetic reasons rather than use ParseTwitterUtils.login(), and we are having to login through the REST API (unless someone has a better idea on how to get a session token for a user with twitterAuth).
So currently it is set up as such:
private class ParseLogin extends AsyncTask<String, String, Boolean> {
JSONObject authData;
JSONObject wrapper;
#Override
protected void onPreExecute() {
try {
authData = new JSONObject();
wrapper = new JSONObject();
JSONObject twitterAuth = new JSONObject();
twitterAuth.put("id", Long.toString(twitterUser.getId()));
twitterAuth.put("screen_name", twitterUser.getScreenName());
twitterAuth.put("consumer_key", CONSUMER_KEY);
twitterAuth.put("consumer_secret", CONSUMER_SECRET);
twitterAuth.put("auth_token", accessToken.getToken());
twitterAuth.put("auth_secret", accessToken.getTokenSecret());
authData.put("twitter", twitterAuth);
wrapper.put("authData", authData);
} catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground(String... args) {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = JSONRequest.SendHttpGet("https://api.parse.com/1/users/", wrapper);
return true;
}
#Override
protected void onPostExecute(Boolean response) {
}
}
Which then in turns sends the login request to the REST API via here
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGetWithEntity httpPostRequest = new HttpGetWithEntity(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("X-Parse-Application-Id", APP KEY);
httpPostRequest.setHeader("X-Parse-REST-API-Key", REST API KEY);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.d("JSON RESULT", resultString);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
Any ideas on the 404?
Edit: Fixed - Use /Users/ instead of /Login/ for 3rd party auth, changes from GET to POST
private class ParseLogin extends AsyncTask<String, String, Boolean> {
JSONObject authData;
JSONObject wrapper;
#Override
protected void onPreExecute() {
try {
authData = new JSONObject();
wrapper = new JSONObject();
JSONObject twitterAuth = new JSONObject();
twitterAuth.put("id", Long.toString(twitterUser.getId()));
twitterAuth.put("screen_name", twitterUser.getScreenName());
twitterAuth.put("consumer_key", CONSUMER_KEY);
twitterAuth.put("consumer_secret", CONSUMER_SECRET);
twitterAuth.put("auth_token", accessToken.getToken());
twitterAuth.put("auth_token_secret", accessToken.getTokenSecret());
authData.put("twitter", twitterAuth);
wrapper.put("authData", authData);
} catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground(String... args) {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = JSONRequest.SendHttpGet("https://api.parse.com/1/users/", wrapper);
return true;
}
#Override
protected void onPostExecute(Boolean response) {
}
And then the Get (which is actually a post, just need to changed the method name)
public static JSONObject SendHttpGet(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("X-Parse-Application-Id", APP ID);
httpPostRequest.setHeader("X-Parse-REST-API-Key", REST API KEY);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.d("JSON RESULT", resultString);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}
Fixed it. Should have been a POST to /Users/ rather than a GET from /Login/. Sharing incase anyone else runs into this.
private class ParseLogin extends AsyncTask {
JSONObject authData;
JSONObject wrapper;
#Override
protected void onPreExecute() {
try {
authData = new JSONObject();
wrapper = new JSONObject();
JSONObject twitterAuth = new JSONObject();
twitterAuth.put("id", Long.toString(twitterUser.getId()));
twitterAuth.put("screen_name", twitterUser.getScreenName());
twitterAuth.put("consumer_key", CONSUMER_KEY);
twitterAuth.put("consumer_secret", CONSUMER_SECRET);
twitterAuth.put("auth_token", accessToken.getToken());
twitterAuth.put("auth_token_secret", accessToken.getTokenSecret());
authData.put("twitter", twitterAuth);
wrapper.put("authData", authData);
} catch (JSONException e)
{
e.printStackTrace();
}
}
#Override
protected Boolean doInBackground(String... args) {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = JSONRequest.SendHttpGet("https://api.parse.com/1/users/", wrapper);
return true;
}
#Override
protected void onPostExecute(Boolean response) {
}
And then the Get (which is actually a post, just need to changed the method name)
public static JSONObject SendHttpGet(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("X-Parse-Application-Id", APP ID);
httpPostRequest.setHeader("X-Parse-REST-API-Key", REST API KEY);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.d("JSON RESULT", resultString);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
}
return null;
}

Android :-Consume a web service through Post method as a json Request and Response

My web service code is following i am using WCF Restful webservices,
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Login?parameter={parameter}")]
string Login(string parameter);
public string Login(string parameter)
{
/*
* input := {"username":"kevin","password":"123demo"}
* output:= 1=sucess,0=fail
*
*/
//Getting Parameters from Json
JObject jo = JObject.Parse(parameter);
string username = (string)jo["username"];
string password = (string)jo["password"];
return ""+username;
}
my client side(Android) code is following
JSONObject json = new JSONObject();
try {
json.put("username","demo");
json.put("password","password123");
HttpPost postMethod = new HttpPost(SERVICE_URI);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
nameValuePairs.add(new BasicNameValuePair("parameter",""+json.toString()));
HttpClient hc = new DefaultHttpClient();
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Exception", ""+e);
}
I am getting following output after calling Web service:
The server encountered an error processing the request. See server
logs for more details.
Basically my problem is I am unable to pass value by using NameValuePair.
Following code worked for me:
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
}
return string;
}

java-calling a method using Apache Http Client

I have a method in spring and I want to access the method using Apache HttpClient.
following is my method :
#PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public #ResponseBody
void createRequisition(#RequestBody CreateRequisitionRO[] request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.debug("Starting createRequisition()...");
for (int i = 0; i < request.length; i++) {
CreateRequisitionRO requisitionRequest = request[i];
// FIXME this has to be removed/moved
requisitionRequest.setFundManager(requisitionRequest.getUserId());
// FIXME might have to search using param level as well
SystemDefault sysDefault = dbFuncs.references.systemDefault
.findByCompanyAndDivisionAndPortfolio(
userContext.getCompany(),
userContext.getDivision(),
requisitionRequest.getPortfolio());
requisitionRequest.setCustodianN(sysDefault.getCustodianN());
gateKeeper.route(requisitionRequest);
}
}
And this is how I log in to the system and make the tomcat run where the application is deployed since the method uses other classes for some functionalities.
I was able to log in to the system without any issues through problematically but i get the following exception -- java.io.EOFException: No content to map to Object due to end of input
This is my main class :
package com.hexgen.reflection;
public class ReflectionWebAPITest {
public static void main(String[] args) {
HttpClientRequests httpRequest = new HttpClientRequests();
String uri="";
try {
uri = "http://localhost:8080/api/trade/createrequisition";
httpRequest.doSubmit("mayank", "hexgen",uri);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
this is my doSubmit Method :
public void doSubmit(String username, String password, String uri) {
HttpClient client = new DefaultHttpClient();
JsonConverter jsonROConverter = new JsonConverter();
CreateRequisitionRO[] request = new CreateRequisitionRO[1];
BigDecimal priceFrom= new BigDecimal("100000");
BigDecimal quantity= new BigDecimal("2");
request[0] = new CreateRequisitionRO();
request[0].setPortfolio("HEXGENFUND");
request[0].setTransSrlNo(new BigDecimal(1));
request[0].setTransCode("BUY");
request[0].setInvestReason("009");
request[0].setInflowOutflow(InflowOutflow.I);
request[0].setTradeDate(new LocalDate());
request[0].setTradeDate(new LocalDate());
request[0].setTradeDateUpto(new LocalDate());
request[0].setTradeTime("11:27:9");
request[0].setInvestCategory("FVTPL");
request[0].setCustodian("DEUTSCHE");
request[0].setHoldType("HOLD");
request[0].setSecurityType(SecurityType.INV);
request[0].setSecurity("DABU02");
request[0].setAssetClass("EQU");
request[0].setIssuer("DABU");
request[0].setMarketType(MarketType.MKT);
request[0].setTradePriceType("");
request[0].setRequisitionType(RequisitionType.SO);
request[0].setPriceFrom(priceFrom);
request[0].setPriceTo(priceFrom);
request[0].setMarketPrice(priceFrom);
request[0].setAveragePrice(priceFrom);
request[0].setPrice(priceFrom);
request[0].setQuantity(quantity);
request[0].setGrossAmtPcy(priceFrom);
request[0].setExchRate(quantity);
request[0].setGrossAmtTcy(priceFrom);
request[0].setNetAmountPcy(priceFrom);
request[0].setNetAmountTcy(priceFrom);
request[0].setAccrIntPcy(priceFrom);
request[0].setAccrIntTcy(priceFrom);
request[0].setAcquCostPcy(priceFrom);
request[0].setYieldType(YieldType.N);
request[0].setPurchaseYield(quantity);
request[0].setMarketYield(quantity);
request[0].setYtm(quantity);
request[0].setMduration(quantity);
request[0].setCurrPerNav(quantity);
request[0].setDesiredPerNav(quantity);
request[0].setCurrHolding(quantity);
request[0].setNoofDays(quantity);
request[0].setRealGlTcy(quantity);
request[0].setRealGlPcy(quantity);
request[0].setNowLater("N");
request[0].setIsAllocable(false);
request[0].setAcquCostReval(quantity);
request[0].setAcquCostHisTcy(quantity);
request[0].setAcquCostHisPcy(quantity);
request[0].setExIntPcy(quantity);
request[0].setExIntTcy(quantity);;
request[0].setAccrIntReval(quantity);
request[0].setAccrIntTcy(quantity);
request[0].setAccrIntPcy(quantity);;
request[0].setGrossAodTcy(quantity);
request[0].setGrossAodPcy(quantity);
request[0].setGrossAodReval(quantity);
request[0].setBankAccAmtAcy(quantity);
request[0].setBankAccAmtPcy(quantity);
request[0].setTaxAmountTcy(quantity);
request[0].setUnrelAmortPcy(quantity);
request[0].setUnrelAmortTcy(quantity);
request[0].setUnrelGlPcy(quantity);
request[0].setUnrelGlTcy(quantity);
request[0].setRealGlHisTcy(quantity);
request[0].setRealGlHisPcy(quantity);
request[0].setTradeFeesTcy(quantity);
request[0].setTradeFeesPcy(quantity);
boolean validateOnly = true;
HttpPost post = new HttpPost("http://localhost:8080/j_spring_security_check");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j_username", username));
nameValuePairs.add(new BasicNameValuePair("j_password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
post.abort();
}
HttpPost postURI = new HttpPost(uri);
// Setup the request parameters
BasicHttpParams params = new BasicHttpParams();
params.setParameter("CreateRequisitionRO", jsonROConverter.serialiseRequisionRO(request));
params.setBooleanParameter("validateOnly", validateOnly);
postURI.setParams(params);
postURI.setHeader("Content-type", "application/json");
HttpResponse responseURL = client.execute(postURI);
} catch (IOException e) {
e.printStackTrace();
}
}
These are the methods which i use to convert the Java POJO to Json;
public JSONArray serialiseRequisionRO(CreateRequisitionRO[] requisitionRO) {
JSONSerializer serializer = new JSONSerializer();
List<String> requisitionROList = new ArrayList<String>();
for(int i = 0 ; i< requisitionRO.length ; i++)
{
requisitionROList.add(serializer.serialize(requisitionRO[i]));
}
System.out.println("JSON : "+serializer.serialize(requisitionRO[0]));
return convertListToJSON(requisitionROList);
}
#SuppressWarnings("unchecked")
public JSONArray convertListToJSON(List<String> requisitionROList){
JSONArray requestCollection = new JSONArray();
JsonFactory jsonFactory = new JsonFactory();
for(int i = 0 ; i< requisitionROList.size() ; i++)
{
requestCollection.add(requisitionROList.get(i));
}
return requestCollection;
}
after doing all these i get the following exception -- java.io.EOFException: No content to map to Object due to end of input
I am in the guessing of that I do not set the parameter correctly I suppose but I am not sure about this.
Please help me to resolve this as I am struggling with this for more than three days.
I got the above java.io.EOFException: No content to map to Object due to end of input it is because the calling expects some argument where as i have sent the request without arguments.and this can also occur i the argument takes json array as parameter but i was sending json string which also was casting me the same exception.

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