json not receiving from server after encoding the URL in Android - java

I am in real trouble. I spent 8 hours on it, but failed. I want to receive json from server using email as a criteria. Here is working part of code in java script: http://jsfiddle.net/7ydnw3ty/1/
When i try to convert it in android, i get empty result. Please let me know, where is the issue. Please, Please, get me out of trouble.
Here is snippet that is calling.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("authtoken", "61d40d3b0395f730d8e24e77cfada8d7"));
nameValuePairs.add(new BasicNameValuePair("zc_ownername","raffbr2"));
nameValuePairs.add(new BasicNameValuePair("criteria", "'Email==\"teste1#gmail.com\"'"));
nameValuePairs.add(new BasicNameValuePair("scope","creatorapi"));
pBar = new ProgressDialog(MainActivity.this);
pBar.setCanceledOnTouchOutside(false);
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pBar.setMessage("Communication With Server, Registering...");
pBar.show();
MyAsyncTask1 mTask = new MyAsyncTask1();
mTask.setOnResultsListener(MainActivity.this);
mTask.execute(getResources().getString(R.string.readserverUrl)+"LoginSecurity1"
, nameValuePairs);**
Async task fot background processing
public class MyAsyncTask1 extends AsyncTask<Object, Integer, String> {
ResultsListener listener;
public void setOnResultsListener(ResultsListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(Object... params) {
// TODO Auto-generated method stub
String res = null;
DefaultHttpClient responseBody = null;
if (params.length > 0) {
String mUrl = params[0].toString();
List<NameValuePair> mParams = (List<NameValuePair>) params[1];
try{
DefaultHttpClient httpclient= new DefaultHttpClient();
HttpPost httpget = new HttpPost(mUrl);
httpget.setEntity(new UrlEncodedFormEntity(mParams, "UTF-8"));
HttpResponse response = httpclient.execute(httpget);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) {
res=line;
System.out.println(line);
}
in.close();
}catch(Exception e){
return res=e.toString();
}
}
return res;
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
if (!listener.equals(null)) {
listener.onResultsSucceeded(result);
}
}
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}

I recommend use Volley lib to solve JSON POST or GET tasks :
Volley example

Related

Sending Https Request But Not Getting Response

I am sending Https request to mysql server but not getting the response while performing the same task on localhost it is working. I have no experience using Https, please give me solution and explain difference between Http and Https request sending to mysql server, hope someone help me thanks in advance.
This is my code
protected String doInBackground(String... params) {
String emailSend = params[0];
String tokenSend = params[1];
String deviceIdSend = params[2];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailSend));
nameValuePairs.add(new BasicNameValuePair("token", tokenSend));
nameValuePairs.add(new BasicNameValuePair("deviceId", deviceIdSend));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://xyz/xyz/xyz.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String resultN) {
super.onPostExecute(resultN);
String s = resultN.trim();
//dialog.dismiss();
if (s.equalsIgnoreCase("success")) {
if (result.contains("Pass")) {

Maintaining session in Android is not working

I am trying to maintain the login info with session in android.
I am sure that all of my codes on the server are OK cause I have tested them with normal web browsers and also the android webview.
I have checked lots of similar questions on stackoverflow but none have worked for me so far.
here is what I have done...
#Override
protected String doInBackground(String... urls) {
try {
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPost = new HttpPost(urls[0]);
httpPost.setEntity(new UrlEncodedFormEntity(params));
//HttpResponse httpResponse = httpClient.execute(httpPost);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = reader.read()) != -1)
sb.append((char) ch);
Content = sb.toString();
} catch (IOException e) {
Log.e("JsonError", e.getMessage());
}
return Content;
}
#Override
protected void onPostExecute(String page_output) {
Dialog.dismiss();
try {
Log.i("data", page_output);
TextView tv = (TextView) context.findViewById(R.id.textView);
tv.setText(Content);
} catch (Exception e) {
e.printStackTrace();
}
}
can you please help me with this?

Android httpclient login to Rails server

I started to learn about how to make an Android application. I tried to connect my app to rails server by using httpclient, however I cannot understand how to connect between app and the remote server.
Here is part of my code, and I matched id form inside "BasicNameValuePair" with html id values. Please let me know how to check whether login is successful or not.
class SendPost extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void... unused) {
String content = executeClient();
return content;
}
protected void onPostExecute(String result) {
}
public String executeClient() {
ArrayList<NameValuePair> post = new ArrayList<NameValuePair>();
post.add(new BasicNameValuePair("user_name", "SallyCook"));
post.add(new BasicNameValuePair("user_email", "domain#ppls.kr"));
post.add(new BasicNameValuePair("user_password", "add123456"));
post.add(new BasicNameValuePair("user_password_confirmation", "add123456"));
post.add(new BasicNameValuePair("user_phone", "01013089579"));
HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
System.out.println(params);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpPost httpPost = new HttpPost("http://www.ppls.kr/users/sign_up");
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(post, "UTF-8");
httpPost.setEntity(entity);
HttpResponse responsePost = client.execute(httpPost);
System.out.println(responsePost.getStatusLine());
HttpEntity resEntity=responsePost.getEntity();
if (resEntity != null) {
Log.w("RESPONSE", EntityUtils.toString(resEntity));
}
return EntityUtils.getContentCharSet(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

500 Internal server when trying to upload image to server

I am working on an application that allows the user to upload an image to server. I am getting 500 internal server error .I cant seem to find anything related to this error which would solve my problem. My code is as follows:
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url){
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bitmap.compress(CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.155.103.167:9090/RestServer/rest/todos");
String fileName = String.format("File_%d.jpg", new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
ContentBody mimePart = bab;
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", bab);
postRequest.setEntity(reqEntity);
postRequest.setHeader("Content-Type", "application/json");
int timeoutConnection = 60000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
System.out.println("Response: " + response.getStatusLine());
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
txt.setText("NEW TEXT"+s);
} catch (Exception e) {
// handle exception here
e.printStackTrace();
System.out.println(e.toString());
}
return null;
}
}
All HTTP 5xx codes indicate a problem on the server side specifically; you're not getting a 4xx error like 400 Bad Request or 413 Request Entity Too Large that indicates that your client code is doing something wrong. Something on the server is going wrong (such as a misconfigured upload directory or a failed database connection), and you need to check your server logs to see what error messages are appearing.
Use this code to upload images It's working fine for me
public class UploadToServer extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args){
String status="";
String URL = "";
try{
Log.d("Image Path ======",TakePicture.file.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
File file = new File(TakePicture.file.toString());
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("Content-Disposition", new StringBody("form-data"));
reqEntity.addPart("name", new StringBody("Test"));
reqEntity.addPart("filename", bin);
reqEntity.addPart("Content-Type", new StringBody("image/jpg"));
httppost.setEntity(reqEntity);
Log.d("Executing Request ", httppost.getRequestLine().toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.d("Response content length: ",resEntity.getContentLength()+"");
if(resEntity.getContentLength()>0) {
status= EntityUtils.toString(resEntity);
} else {
status= "No Response from Server";
Log.d("Status----->",status);
}
} else {
status = "No Response from Server";
Log.d("Status----->",status);
}
} catch (Exception e) {
e.printStackTrace();
status = "Unable to connect with server";
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
}
}

Send key-value parametres and json message body throught http post request

I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories