Login android project into localhost server - json

This is my Code:
public void CheckUserNameandPwd() {
// TODO Auto-generated method stub
String username = u.getText().toString().trim();
String pwd=pwdd.getText().toString().trim();
if(username.length()==0){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Fill UserName!");
dlgAlert.setTitle("Error");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
return;
}
else if(pwd.length()==0 ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Fill Password!");
dlgAlert.setTitle("Error");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
return;
}
else{
if(verifyLogin(username,pwd)){
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this,MainActivity.class));
}else{
Toast.makeText(getApplicationContext(),"error occur!",Toast.LENGTH_SHORT).show();
// startActivity(new Intent(Login.this,mainlayout_activity.class));
}
}
}
private boolean verifyLogin(St
ring username, String pwd) {
try{
showpDialog();
DefaultHttpClient httpclient=new DefaultHttpClient();
HttpGet httpget=new HttpGet("http://127.0.0.1:8083/MyService.svc/LoginForUsers?UserName=" + username + "&Password=" + pwd);
HttpResponse httpresponse=httpclient.execute(httpget);
HttpEntity httpentity=httpresponse.getEntity();
InputStream stream=httpentity.getContent();
String result=ConvertStreamToString(stream);
if(result.charAt(1)=='1'){
hidepDialog();
return true;
}else {
hidepDialog();
return false;
}
}catch (Exception e){
hidepDialog();
return false;
}
}
private String ConvertStreamToString(InputStream is) {
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
String line=null;
try
{
while ((line=reader.readLine())!=null){
sb.append(line+"\n");
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

Never use a GET request to your server if you have a password on the url!!
Here's a POST request that may help you. Taken from here
...
// Create data variable for sent values to server
String data = URLEncoder.encode("user", "UTF-8")
+ "=" + URLEncoder.encode(Login, "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8")
+ "=" + URLEncoder.encode(Pass, "UTF-8");
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://androidexample.com/media/webservice/httppost.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
...

Related

decompress Apache httpclient results

I'm using Apache HTTPClient 4.5.3 to make some HTTP requests, but I am getting a g-zipped response I have tried many things I found online but non of them worked. I still get gibberish when I print the response. Below are the relevant code. What do I need to do to get a human readable response?
static public CloseableHttpClient CreateHttpClient() {
// return
// HttpClients.custom().disableAutomaticRetries().setHttpProcessor(HttpProcessorBuilder.create().build())
// .build();
return HttpClientBuilder.create().disableAutomaticRetries()
.setHttpProcessor(HttpProcessorBuilder.create().build()).build();
}
static public RequestConfig GetConfig() {
return RequestConfig.custom().setSocketTimeout(READTIMEOUT).setConnectTimeout(CONNECTTIMEOUT)
.setConnectionRequestTimeout(REQUESTTIMEOUT).build();
}
static public String updates() {
String result = "";
String url = "https://example.com";
CloseableHttpClient httpClient = CreateHttpClient();
CloseableHttpResponse response = null;
URL urlObj;
RequestConfig config = GetConfig();
try {
urlObj = new URL(url);
HttpPost request = new HttpPost(url);
request.setConfig(config);
StringEntity params = new StringEntity("example");
request.addHeader("Accept-Language", "en");
request.addHeader("Content-Type", "application/json; charset=UTF-8");
request.addHeader("Content-Length", String.valueOf(params.getContentLength()));
request.addHeader("Host", urlObj.getHost());
request.addHeader("Connection", "Keep-Alive");
request.addHeader("Accept-Encoding", "gzip");
request.setEntity(params);
response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("updates response code: " + responseCode);
// BufferedReader rd = new BufferedReader(new
// InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = EntityUtils.toString(response.getEntity());
// String line = "";
// while ((line = rd.readLine()) != null) {
// result.append(line);
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You should get the content from the response entity which is an InputStream. Than you could create a String from that InputStream with BufferedReader
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertInputStreamToString(instream);
instream.close();
}
Write your own convertInputStreamToString. If you need help for doing that check here:
Read/convert an InputStream to a String

Java/Android: Backslashes in JSON in Double Quotation places

I try to send "POST" request to serwer. Request includes JSON. Server returns "ok" or my JSON (in value of "message" key), if data in not correct. And I get strange backslashes ( \ sing) in my JSON, sent to server.
I get JSON response:
{"message":{"{\"phone_number\":\"_380661111111\",\"password\":\"112233aa\",\"military_id\":\"12345\",\"email\":\"won#mail_ru\"}":""}}
Normal JSON:
{"phone_number":"380666320670","password":"112233aa","military_id":"12345","email":"wovilon#mail.ru"}
Full code:
class SendLoginData extends AsyncTask<Void, Void, Void> {
String[] key,value;
String mResultString;
SendLoginData(String[] inKey, String[] inValue ){
this.key=new String[inKey.length];
this.value=new String[inValue.length];
this.key=inKey;
this.value=inValue;
}
String resultString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {// http://oasushqg.beget.tech/users
String myURL = "http://y937220i.bget.ru/users";
byte[] data = null;
InputStream is = null;
try {
URL url = new URL(myURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
for (int i=0; i<this.key.length; i++) {
jsonParam.put(this.key[i], this.value[i]);
}
data=jsonParam.toString().getBytes("UTF-8");
os.write(data);
Log.d("MyLOG", "data is next: "+new String(data, "UTF-8"));
data = null;
conn.connect();
int responseCode= conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (responseCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
JSONObject jsonObj=new JSONObject(resultString);
mResultString=jsonObj.getString("message");
} else {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(resultString != null) {
Log.d("MyLOG", "postExecute run");
Log.d("MyLOG", mResultString);
}
}}

Converting finalBufferData into img url to display

I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.

Use URLConnection instead of HttpClient in android studio

Is there any way to convert this code into URLCOnnection instead of using Httpclient ? Im using API23 and HTTP CLient is not supported anymore. I have a hard time using URLCOnnection because almost all the tutorials uses HttpClient for connection. thanks
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://myphpmysqlweb.hostei.com/loginpost.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
This is the basic format for URLConnection that I merged from some working code of mine with yours. If you fill in your code where I've specified, it should work.
//-------------------
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;
InputStream is = null;
try {
URL url = new URL(link);
URLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//FILL IN YOUR CODE HERE!
//FILL IN YOUR CODE HERE!
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
//-------------------

Blackberry how to get Json Response (java)

I want to get a JSON response on the simulator. How can I read JSON from the server?
public void run()
{
HttpConnection httpConn;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://example.com/login.php");
if (connDesc != null)
{
try {
httpConn = (HttpConnection)connDesc.getConnection();
final int iResponseCode = httpConn.getResponseCode();
Dialog.alert("Type: "+httpConn.getType());
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " + Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
HttpConnection connection = (HttpConnection)Connector.open(urlConection);
InputStream inputStream = connection.openInputStream();
if(connection.getResponseCode() == HttpConnection.HTTP_OK){
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
int readCharacter;
StringBuffer responseBuffer = new StringBuffer();
while ((readCharacter = reader.read()) != -1) {
responseBuffer.append((char) readCharacter);
connection.close();
inputStream.close();
reader.close();
String responseMessage = new String(responseBuffer);
}
}
You need to create JSONObject for the response.
try {
JSONObject object = new JSONObject(responseMessage);
} catch (JSONException e) {
e.printStackTrace();
}