HttpClient can't connect to database [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having some trouble with the connection to my database, I could need some help to see if it's the .java file that is wrong or my .php file. The result right now is "couldn't connect to database"
.php file http://pastebin.com/9fMmzprd
.java:
package com.example.stolle.httpclient;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class contact extends Activity {
TextView resultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
StrictMode.enableDefaults();
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result ="";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://stolle.se.preview.citynetwork.se/kontaktApp/read_allcontacts.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (Exception e){
Log.e("log_tag","Error in http connection"+e.toString());
resultView.setText("Couldnt connect to database");
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line=reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag","Error converting result"+e.toString());
}
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length(); i++){
JSONObject json = jArray.getJSONObject(i);
s = s+
"id : "+json.getInt("id")+"\n"+
"name : "+json.getString("name")+"\n"+
"mail : "+json.getString("mail")+"\n"+
"company :"+json.getString("company")+"\n\n";
}
resultView.setText(s);
}
catch (Exception e){
//to do handle exception
Log.e("Log_tag", "Error Parsing Data" + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Your problem is not with PHP. Your PHP file is working good. Your error is at httppost request section. You dont have a setEntity which is required. Look here for details.
I can give a example of Httppost request with name value pair.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("test","123"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("URL");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}

Related

HTTP post request returns HTML code instead of JSON data

I am trying to develop a simple client-server application in Android. I have a problem while fetching a response from PHP code. It returns an HTML code instead of JSON. Is it a problem with the WAMP server I have used?
Here is the PHP code:
<?php
include_once './connect_db.php';
$db = new DBConnect();
$response = array();
$username = $_POST["username"];
$password = $_POST["password"];
if (empty($_POST['username']) || empty($_POST['password']))
{
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty.";
die(json_encode($response));
}
$query = " SELECT * FROM account WHERE username = '$username'and password='$password'";
$sql1 = mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row))
{
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
mysql_close();
?>
login.java:
package com.example.rossh.register;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity implements OnClickListener {
private EditText user, pass;
private Button login;
JSONObject jsonObject;
String response;
// Progress Dialog
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//setup buttons
login = (Button) findViewById(R.id.btnlogin);
//register listeners
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnlogin:
String username = user.getText().toString();
String password = pass.getText().toString();
boolean cancel =false;
View focusView = null;
if(TextUtils.isEmpty(username))
{
user.setError("This field is required!!");
cancel=true;
focusView=user;
}
if(TextUtils.isEmpty(password))
{
pass.setError("This field is requird!!!");
cancel=true;
focusView=pass;
}
if(cancel)
{
focusView.requestFocus();
} else {
new AttemptLogin().execute(username, password);
}
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login.this);
pDialog.setMessage("Attempting login...");
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
String username = args[0];
String password = args[1];
// Building Parameters
final int success;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JsonParser jsonParser = new JsonParser();
jsonObject = jsonParser.makeHttpRequest(AppConfig.LOGIN_URL, "POST", params);
if (jsonObject != null) {
try{
Log.d("Json data",">"+jsonObject);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
response = jsonObject.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", jsonObject.getString(TAG_MESSAGE));
response = jsonObject.getString(TAG_MESSAGE);
}
} catch(JSONException e) {
e.printStackTrace();
}
}
return response;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(login.this, "ok", Toast.LENGTH_LONG).show();
}
}
}
}
}
jsonParser.java:
package com.example.rossh.register;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
public class JsonParser {
InputStream is = null;
static String json = "";
static JSONObject jObj = null;
// constructor
public JsonParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Content-Type","application/json");
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, HTTP.UTF_8), 8);
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 {
JSONArray jsonarray = new JSONArray(json);
jObj = jsonarray.getJSONObject(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing " + e.toString());
}
// return JSON String
return jObj;
}
}
It may be due to one or more errors in your HTML, or if your page returns non-text objects. Make sure your HTML webpage does not throw an error while running from browser.
For one thing I would suggest that your PHP script sets proper content type when returning json, see Returning JSON from a PHP Script. Also see Java HttpRequest JSON & Response Handling for how to do JSON requests in java.
Try changing die(json_encode($response)) to echo json_encode($response)

Error parsing data org.json.JSONException: Value <br of type java.lang.String

I've been working out an android application with login connected to a local database. The code works perfectly fine when I input values which can be found in the table. However, when I'm trying some random inputs, it produces an error: Error parsing data org.json.JSONException: Value
I've searched many times but I cant figured how to solve this problem. Please help me.
config.inc.php
$username ="root";
$password ="";
$dbname = "sample";
$host="localhost";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $e)
{
die("Failed to connect to the database:" . $e->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_prc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach ($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-type: text/html; charset=utf-8');
session_start();
?>
login.php
<?php
//load and connect to MySQL database stuff
require 'config.inc.php';
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $e) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:
<input type="text" name="username" placeholder="username" />
Password:
<input type="password" name="password" placeholder="password" value="" />
<input type="submit" value="Login" />
</form>
<?php
}
?>
login.java
package com.example.piasi_pc1.phrism;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import android.os.AsyncTask;
public class Login extends AppCompatActivity {
EditText et_username, et_password;
Button btnlogin;
ImageView pass_visible;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL =
"http://192.90.100.205/webservice_phrism/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
et_username = (EditText) findViewById(R.id.username);
et_password = (EditText) findViewById(R.id.password);
btnlogin = (Button) findViewById(R.id.login_btn);
pass_visible = (ImageView) findViewById(R.id.img_visible);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
});
pass_visible.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
et_password.setInputType(InputType.TYPE_CLASS_TEXT);
break;
case MotionEvent.ACTION_UP:
et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
break;
}
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = et_username.getText().toString();
String password = et_password.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, Dashboard.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser.java
package com.example.piasi_pc1.phrism;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
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;
}
}
I know the answer already.
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}else
{$login_ok = false; <------missing value
}
}

IOUtils writer error Java connect to GAE

I import writer from apache. The error occured when I try using it.
in is just the url.
I was following exactly what was on this link:
Store image to Blobstore from android client and retrieve blobkey and upload url to store in Datastore. - GAE
Does someone know this error?
UPDATED
Here is the full code:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.api.client.util.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class GetBlobUrlTask extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_blob_url_task);
}
#Override
protected Void doInBackground(Void... arg0){
HttpClient httpClient = new DefaultHttpClient();
//This will invoke "ImgUpload servlet
HttpGet httpGet = new HttpGet("http://PUT_YOUR_URL_HERE/bloburlget");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity urlEntity = response.getEntity();
InputStream in = urlEntity.getContent();
String str = "";
StringWriter writer = new StringWriter();
String encoding = "UTF-8";
IOUtils.copy(in, writer, encoding);
str = writer.toString();
HttpPost httppost = new HttpPost(str);
File f = new File(picturePath);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.addBinaryBody("photo", f, ContentType.create("image/jpeg"), "foto2.jpg");
httppost.setEntity(reqEntity.build());
response = httpClient.execute(httppost); //Here "uploaded" servlet is automatically invoked
str = EntityUtils.toString(response.getEntity());
JSONObject resultJson = new JSONObject(str);
blobKey = resultJson.getString("blobKey");
servingUrl = resultJson.getString("servingUrl");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_get_blob_url_task, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My guess is the person in the example is using IOUtils from Apache Commons and you are using a different IOUtils provided by the Google HTTP client

Http Post Request

i am developing an android app, which needs to send a string to web server(written in java).when server receives this string it will automatically fire response.after going through many examples i tried to do this .
i used following code to send request.
try{
String url = "https://mywebserver";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "014500000000000000000000** 0000 0030000100700006800006000000000000000 0 I 00000000 00000000000000000000000000000000000073054721143";
// Send post request
con.setDoOutput(true);
//something is wrong after this line
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}catch(Exception e){
tv_str.setText("caught exception");
}
this is not working (generating an exception). and i also tried this example- answer 2 but not working and
also, is there any webserver for Testing http post requests. i.e how do i test my request
if there is any other way to do this please tell me as i am new to this
my logcat:
07-08 11:59:37.423: D/dalvikvm(31971): Late-enabling CheckJNI
07-08 11:59:37.713: I/Adreno-EGL(31971): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
07-08 11:59:37.713: I/Adreno-EGL(31971): OpenGL ES Shader Compiler Version: 17.01.10.SPL
07-08 11:59:37.713: I/Adreno-EGL(31971): Build Date: 12/04/13 Wed
07-08 11:59:37.713: I/Adreno-EGL(31971): Local Branch: workspace
07-08 11:59:37.713: I/Adreno-EGL(31971): Remote Branch:
07-08 11:59:37.713: I/Adreno-EGL(31971): Local Patches:
07-08 11:59:37.713: I/Adreno-EGL(31971): Reconstruct Branch:
07-08 11:59:37.764: D/OpenGLRenderer(31971): Enabling debug mode 0
07-08 11:59:37.849: E/Adreno-ES20(31971): <gl_external_unsized_fmt_to_sized:2379>: QCOM> format, datatype mismatch
07-08 11:59:37.849: E/Adreno-ES20(31971): <get_texture_formats:3009>: QCOM> Invalid format!
thanks in advance
yes json is easy. i implemented this and its working fine.. thanks to JLONG and user1369434.
package m.example.postrwq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
Button btnPost;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPost = (Button) findViewById(R.id.button1);
tvIsConnected = (TextView) findViewById(R.id.textView1);
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
btnPost.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "my string";
// 6. set json to StringEntity
StringEntity se = new StringEntity(json);
// 7. set httpPost Entity
httpPost.setEntity(se);
// 8. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 9. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 10. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 11. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 12. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected() {
// TODO Auto-generated method stub
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
hope this will help others
Just a hint for you: I think it would be easier to use JSON in combination with GSON (instead of a simple String) to transport your data between the app and the webserver.
Do you really need to use HTTPS? If yes I guess you should set SSLSocketFactory for your connection after opening it. Check this answer for more info: https://stackoverflow.com/a/16507195/1407451
I also would like to recomend you not use HttpsURLConnection itself but take look at some libraries for network comunications like Retrofit or Volley. For me it seems to be much easer to use.
I use a JSON parser java class, because it is much easier to transport data from the app and server just like user1369434 said. I forgot where I got the code but here it is, create a java class named JSONparser then post this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
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;
}
}
Then on your Activty do this:
public class YOUR ACTIVITY extends Activity {
JSONParser jParser = new JSONParser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a Asynctask for the http request
new NAMEOFYOURASYNCTASK().execute();
}
}
and on your asynctask:
class YOURASYNCTASK extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username_GET", dealer_user_name ));
// getting JSON string from URL
json = jParser.makeHttpRequest(YOUR URL HERE, "POST", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
modify your php code to throw JSON files back to the app and. like this:
// array for JSON response
$response = array();
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
you get the idea. this is just a suggestion btw.

How to make a "raw" string out of JSON in Java

I am coding an android app for school atm. i am stock and want to ask you guy to help me.
So far i understand how to use PHP to print data from a MySQL database ready to be parset in Java. Then my code(taken from here: http://www.helloandroid.com/tutorials/connecting-mysql-database)takes the data and converts it into strings i believe.
So my question is: how do i for eksample make and if statement to check if the userdata is correct? i just dont get it!
Here is all my code for the activity(login form) i use:
package com.example.fungi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//Intent i = new Intent(getBaseContext(), MainPageActivity.class);
//startActivity(i);
Button login;
EditText username;
EditText password;
TextView lol;
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ActionBar actionBar = getActionBar();
//actionBar.hide();
lol = (TextView) findViewById(R.id.textView1);
login = (Button) findViewById(R.id.loginbutton);
username = (EditText) findViewById(R.id.usernametext);
password = (EditText) findViewById(R.id.passwordtext);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String usernameget = username.getText().toString();
String passwordget = password.getText().toString();
if(usernameget.contentEquals("")){
username.setText("usernam required");
}else {
if(passwordget.contentEquals("")){
username.setText("password required");
}else {
String userid = username.getText().toString();
Intent intent = new Intent(getBaseContext(), Side.class);
intent.putExtra("sessionid", userid);
startActivity(intent);
}
}
}
});
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(result, result));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://http://fungi.webatu.com/Index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e11){
Log.e("log_tag", "Fejl i HTTP connection "+e11.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Fejl i resultat konvertering "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", username: "+json_data.getString("username")+
", password: "+json_data.getString("password")+
", alder: "+json_data.getInt("alder"));
//maybe if statement here?
;
}
}
catch(JSONException e1){
Log.e("log_tag", "Error parsing data "+e1.toString());
}
}
}
thanks in advance!!
I'm not sure about your issue, but I think you want to get some JSON data from a webservice.
Developing to Android, you cannot use network resources on the main thread. So you will need to start a new thread. To reach that, you can use AsyncTask or use the Thread class.
public static JSONArray getJSONArrayFromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
Log.d("URL_SEARCH", url);
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
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 + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jArray = new JSONArray(result);
Log.d("URL_SEARCH", "JSON: " + jArray.length());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}

Categories