Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to create a simple web service between my Android App and Java Servlet. The response that I return from the servlet is JSONObject but what I'm recieving in my Android app is boolean. The code for both the servlet and android is given.
ANDROID CODE
class ExecuteTask extends AsyncTask<Void, Void, Void> {
String param;
#Override
protected Void doInBackground(Void... params) {
try {
param = "param1=" + URLEncoder.encode(_username, "UTF-8") + "¶m2=" + URLEncoder.encode(_password, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL(url_login);
} catch (Exception e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = null;
try {
out = new PrintWriter(conn.getOutputStream());
out.print(param);
Log.d("Checking Params", param);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
String response = "";
Scanner inStream = null;
// Log.d("JSON", json.toString());
try {
int responseCode = conn.getResponseCode();
if(responseCode ==200){
// conn.setDoInput(true);
inStream = new Scanner(conn.getInputStream());
}else{
InputStream in = null;
in = conn.getErrorStream();
}
}catch (IOException e) {
e.printStackTrace();
}
while (inStream.hasNextLine()) {
response += (inStream.hasNextLine());
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String s = json.getString("Login");
Log.d("MSG", s);
if (s != null) {
Intent intent = new Intent(LoginActivity.this, DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.d("Msg sent", s);
finish();
} else if (s.equals("fail")) {
Toast.makeText(context, "Unable to load the schedule", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
conn.disconnect();
}
return null;
}
}
RUNQUERY METHOD
public JSONObject RunQuery(String[] params, HttpServletRequest request, HttpServletResponse response) {
// System.out.println("The parameters are: " + params[0] + params[1] +
// params[2]);
String sql = "SELECT * FROM job_recommender.user where User_Name='"+ params[0] +"' AND password='"+ params[1] +"'";
// System.out.println("Our SQL Statement is " + sql);
JSONObject json = new JSONObject();
// JSONArray jArray = null;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (rs.next()) {
System.out.println("This is RS" + rs);
JSONObject jObj = new JSONObject();
jObj.put("username", (new String(rs.getString("User_Name"))));
jObj.put("password", (new String(rs.getString("password"))));
System.out.println(jObj);
json.put("Login", jObj);
System.out.println(json.put("Login", jObj));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("This is our JSON" + json);
response.setContentType("Content-Type=application/json");
response.setCharacterEncoding("charset=UTF-8");
PrintWriter out;
try {
System.out.println("response JSON" + json.toString());
out = response.getWriter();
out.println(json);
//response.getWriter().write(json.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
SERVLET
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.setContentType("text/html");
Enumeration paramNames = request.getParameterNames();
//System.out.println(paramNames);
String params[] = new String[2];
int i = 0;
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
System.out.println("Checking ParamNames" + paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];
ulogin.setUsername(params[0]);
ulogin.setPassword(params[1]);
// System.out.println(params[i]);
i++;
}
String name = ulogin.getUsername();
String password = ulogin.getPassword();
System.out.println("username" + name + "password" + password);
WebServiceDAO wdao = new WebServiceDAO(getServletContext());
wdao.RunQuery(params, request, response);
response.getWriter().append("Served at: ").append(request.getContextPath());
}
Can anyone tell me what I'm doing wrong here? I have tried every way I could think of to fix this. Any help would be useful to me.
There's a typo in your code
response += (inStream.hasNextLine());
Should probably be
response += (inStream.nextLine());
Related
I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.
I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";
it my method call
if(guest){
new JsonTask().execute("URL");
}else{
new AsyncTaskGetMareker().execute();
}
This is my method:
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
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+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
JSONObject json = new JSONObject(result);
JSONObject jsonResponse = json.getJSONObject("response");
String name = jsonResponse.getString("store_name");
String lat = jsonResponse.getString("latitude");
String lang=jsonResponse.getString("longitude");
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
This is my error
org.json.JSONException: Value [{"id":1,"store":"дом","category_id":11,"latitude":
2020-02-10 14:24:01.689 13767-13767/? W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
I found this code on this site and am trying to implement it in my project.
I make sure that when checking, either a local or external file is loaded.
What i do wrong in my code?Please help me...I don't understand English well, please understand and forgive me
The answer that helped me from: mrgrechkinn
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result !=null){
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObject= null;
try {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("store_name");
String lat = obj.getString("latitude");
String lang=obj.getString("longitude");
String desc=obj.getString("store_desc");
String oxr=obj.getString("telephone");
String sost=obj.getString("keywords");
int cat=obj.getInt("category_id");
int id=obj.getInt("id");
Log.e("100rad",""+i);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I am using httpurlconnection and I can't find understandeble way to parse my json.
attribute output return this json {"value":"SUCCESS"}
but how to parse the json?
code
protected Void doInBackground(String... params) {
String ue=params[1];
try {
//final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL("my url return json ");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
String urlParameters = "e="+ue;
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
final StringBuilder output = new StringBuilder("Request URL " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//output;
try {
JSONObject json = new JSONObject(output.toString());
message = json.optString("value");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(register.this,"output: "+output, Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
progress.dismiss();
}
if there is any dependences that I should to add to gradel.Please, let me know! thank you in advance
Simplest way:
try {
JSONObject json = new JSONObject(output); // output string
String message = json.optString("value"); // SUCCESS
} catch (JSONException e) {
e.printStackTrace();
}
But I would recommend to use Gson.
I new to android and want to call web service written in PHP from android application; but I am getting InputStream as null. But when I tried to run same URL from browser it is showing the output.
My php file: (userlogin.php)
<?php
$con=mysqli_connect("IP Address of server","Any","","user");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT * FROM userLogin where username = '$username' and password = '$password'");
$n_filas = mysqli_num_rows ($result);
$array = array();
for ($i=0; $i<$n_filas; $i++)
{
$fila = mysqli_fetch_array($result);
$array[$i]['username'] = utf8_encode($fila['username']);
$array[$i]['password'] = utf8_encode($fila['password']);
}
$result= json_encode($array);
echo $result;
mysqli_close($con);
?>
and my JSON parser :
public JSONArray makeHttpRequest(String url, ArrayList<String> params) {
try
{
URL url1 = new URL("http://IP ADDRESS OF SERVER/userlogin.php?username="+params.get(0)+"&password="+params.get(1));
urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.d("String is",is.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("String ===",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
Log.d("In JSON Object try ", "yes");
jObj = new JSONArray(json);
Log.d("String Json ===",jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Any help will be appreciated. Thank You.
The following works for me:
public static void retrieveData() {
try {
// the following line is BAD - do not supply username + password via such an insecure connection!
URL url1 = new URL("http://IP ADDRESS OF SERVER/userlogin.php?username="+params.get(0)+"&password="+params.get(1));
URLConnection urlConnection = url1.openConnection();
// you may want to adjust the timeout here, like so:
// urlConnection.setConnectTimeout(timeout);
urlConnection.connect();
try (InputStream is = urlConnection.getInputStream()) {
processData(is);
} catch (IOException e) {
// do something smart
}
} catch (MalformedURLException e) {
// do something smart
} catch (IOException e) {
// do something smart
}
}
private static void processData(InputStream is) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// rest of your processing logic
} catch (IOException e) {
// do something smart
}
}
These methods do not necessarily have to be static and you may of course amend their signature (parameters, return value) to suit your needs.
I am having some problem when trying to access MySQL from Android via Servlet. What I am trying to do is check if the event exist in database by passing some value to servlet class. If no existing record, then perform DB insertion.
public void createEvent(Event event) {
String page;
JSONArray jsonArray;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "checkEventExist");
List<NameValuePair> checkExistnvp = new ArrayList<NameValuePair>(3);
checkExistnvp.add(new BasicNameValuePair("eventName", event.getEventName()));
checkExistnvp.add(new BasicNameValuePair("eventX", event.getEventX()));
checkExistnvp.add(new BasicNameValuePair("eventY", event.getEventY()));
try {
post.setEntity(new UrlEncodedFormEntity(checkExistnvp));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
page = "{\'Events\':" + responseString + "}";
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
if(length == 0){
// If no existing record, then perform DB insertion
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
And inside my servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
if (request.getParameter("checkEventExist") != null) {
String eventX = request.getParameter("eventX");
String eventY = request.getParameter("eventY");
String eventName = request.getParameter("eventName");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/mydb", "root", "root");
PreparedStatement statement = con
.prepareStatement("SELECT * FROM event WHERE eventName = '" + eventName + "' AND eventX = '" + eventX + "' AND eventY = '"+ eventY + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
JSONObject eventInfo = new JSONObject();
eventInfo.put("eventName", result.getString("eventName"));
eventInfo.put("eventX", result.getString("eventX"));
eventInfo.put("eventY", result.getString("eventY"));
jsonArray.put(eventInfo);
}
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
}
}
I not sure how should I pass and get name/value pairs into the doGet() in servlet. With this line:
post.setEntity(new UrlEncodedFormEntity(checkExistnvp));
It's how I pass value into the doPost(). But I need to pass it to doGet() instead. Any guides?
Thanks in advance.
You should use query parameters since HTTP GET does not allow sending entity in HTTP Body.
In order to send parameters for the HTTP GET, you should prepare a URL like this:
HttpGet request = new HttpGet(ENeighbourhoodActivity.URL + "checkEventExist?" +
"eventName=<eventName>&"+
"eventX=<eventX>&"+
"eventY=<eventY>");
HttpResponse response = client.execute(request);
And you shouldn't add any NameValuePair to the request