I have an application hosted on "heroku". It has this method you call it via a get and it will respond with a "Json code"
public static Result renderManga(int id) {
Manga m = Manga.find.byId(id);
if (m != null) {
return ok(Json.toJson(m));
} else
return null;
}
}
route file
GET /srvc/manga/:id controllers.Services.renderManga(id:Integer)
now my android code
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://boku-no-manga.herokuapp.com/srvc/manga/5"));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
EditText res = (EditText) findViewById(R.id.result);
res.setText(responseString);
Log.i("JSONmymanga",responseString);
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {}
I want to receive that JSON code sent by my play app and work with it in my android app.
Try this code,
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ServerTest extends Activity {
private String TAG = "test";
private String url = "https://boku-no-manga.herokuapp.com/srvc/manga/5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
}
}
}
Also make sure you have added this to manifest,
<uses-permission android:name="android.permission.INTERNET" />
Related
i was trying to create an online apps. I would like to send a string from my apps to my PHP script, but it ended up with the php doesn't receive any string from my apps, which means the PhP will echo back NULL. I have been doing research online and searching for solution, but none of them worked.
Below is my MainActivity.java code:
package my.com.tutionathome.calvinlau.testserver;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b;
EditText et;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
et= (EditText)findViewById(R.id.EditText01);
tv= (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
Thread thread = new Thread()
{
#Override
public void run() {
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $"username" = $_POST['username'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
tv.setText("Response from PHP : " + response);
}
});
}catch(Exception e){
runOnUiThread(new Runnable() {
public void run() {
p.dismiss();
}
});
System.out.println("Exception : " + e.getMessage());
}
}
};
thread.start();
}
});
}
}
And my php code:
<?php
// put your code here
$hostname_localhost ="localhost";
$database_localhost ="android";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select Email, Username from tblmember where Username = '".$username."' AND Email = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($username == NULL){
echo "NULL";
}else{
echo $username;
}
?>
This is my Android Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.com.tutionathome.calvinlau.testserver">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
There are a bunch of libraries to facilitate this, saving many lines of code, i particularly suggest retrofit.
Try this Code.
AysncyTask
private class AysncyTask extends AsyncTask<Void,Void,Void>
{
private ProgressDialog regDialog=null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
regDialog=new ProgressDialog(this);
regDialog.setTitle(getResources().getString(R.string.app_name));
regDialog.setMessage(getResources().getString(R.string.app_pleasewait));
regDialog.setIndeterminate(true);
regDialog.setCancelable(true);
regDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
et.getText().toString().trim()));
postParameters.add(new BasicNameValuePair("password",
etpass.getText().toString().trim()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php",
postParameters);
res = response.toString();
return res;
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(3000);
// error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
}
} catch (Exception e) {
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(regDialog!=null)
{
regDialog.dismiss();
//do you code here you want
}
// do what u do
}
SimpleHttpClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpatch(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
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)
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.
I need to upload an xml file from my android application to a remote host. I found this code and get the library from here. but I got this error:
02-17 22:06:41.144: E/AndroidRuntime(21644): FATAL EXCEPTION: main
02-17 22:06:41.144: E/AndroidRuntime(21644): java.lang.NoClassDefFoundError: org.apache.http.entity.mime.HttpMultipart
02-17 22:06:41.144: E/AndroidRuntime(21644): at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:77)
02-17 22:06:41.144: E/AndroidRuntime(21644): at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:100)
and here is my upload method.
private void upload(String filepath)
{
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://myurl.com/");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "application/xml");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Am I using a bad mime type or download wrong library?
Any solution?
Thanks
I found a new example here that upload an image to php server using php script. so I changed it for uploading xml file.
Android Activity: UploadXmlFile.java
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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 android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class UploadXmlFile extends Activity {
InputStream inputStream;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String the_string_response;
int contentLength;
String res = "";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_upload_image);
// create xml content
String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?><langs><lan><id>1</id><name>java</name></lan><lan><id>2</id><name>c++</name></lan><lan><id>3</id><name>python</name></lan><lan><id>4</id><name>php</name></lan></langs>";
nameValuePairs.add(new BasicNameValuePair("xmldata",xmldata));
nameValuePairs.add(new BasicNameValuePair("filename","myfile.xml"));
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your-url.com/upload_xml_file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});
}catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "Error " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("Error in http connection ",e.toString());
}
}
});
t.start();
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
}
});
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(UploadXmlFile.this, "Result : " + res, Toast.LENGTH_LONG).show();
}
});
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
PHP file: upload_xml_file.php
<?php
$base=$_REQUEST['xmldata'];
$fname=$_REQUEST['filename'];
header("Content-Type: text/xml; charset=utf-8");
$file = fopen($fname, 'wb');
fwrite($file, $base);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
upload the php file on server and set INTERNET permission for android application.
Hope help for others.
Please refer to the following code which continuously calls a new AsyncTask. The purpose of the AsyncTask is to make an HTTP request, and update the string result.
package room.temperature;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
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 android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class RoomTemperatureActivity extends Activity {
String result = null;
StringBuilder sb=null;
TextView TemperatureText, DateText;
ArrayList<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TemperatureText = (TextView) findViewById(R.id.temperature);
DateText = (TextView) findViewById(R.id.date);
nameValuePairs = new ArrayList<NameValuePair>();
for (int i = 0; i < 10; i++) {
RefreshValuesTask task = new RefreshValuesTask();
task.execute("");
}
}
// The definition of our task class
private class RefreshValuesTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/roomtemp/tempscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine());
is.close();
result=sb.toString();
}
catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//System.out.println(result);
setValues(result);
}
}
public void setValues(String resultValue) {
System.out.println(resultValue);
String[] values = resultValue.split("&");
TemperatureText.setText(values[0]);
DateText.setText(values[1]);
}
}
The problem I am experiencing relates to the AsyncTask in some way or the function setValues(), but I am not sure how. Essentially, I want each call to the AsyncTask to run, eventually in an infinite while loop, and update the TextView fields as I have attempted in setValues. I have tried since yesterday after asking a question which led to this code, for reference.
Oh yes, I did try using the AsyncTask get() method, but that didn't work either as I found out that it is actually a synchronous call, and renders the whole point of AsyncTask useless.
Use publishProgress(), and onProgressUpdate() methods, to publish progress, while executing some task in doInBackground() method.
so change your code to following:
package room.temperature;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
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 android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class RoomTemperatureActivity extends Activity {
String result = null;
StringBuilder sb=null;
TextView TemperatureText, DateText;
ArrayList<NameValuePair> nameValuePairs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TemperatureText = (TextView) findViewById(R.id.temperature);
DateText = (TextView) findViewById(R.id.date);
nameValuePairs = new ArrayList<NameValuePair>();
RefreshValuesTask task = new RefreshValuesTask();
task.execute("");
}
// The definition of our task class
private class RefreshValuesTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
for (int i = 0; i < 10; i++) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/roomtemp/tempscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine());
is.close();
result=sb.toString();
publishProgress(result);
}
catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
return result;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setValues(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//System.out.println(result);
setValues(result);
}
}
public void setValues(String resultValue) {
System.out.println(resultValue);
String[] values = resultValue.split("&");
TemperatureText.setText(values[0]);
DateText.setText(values[1]);
}
}