HTTP Get Request in Android json - java

Hi, i don't undestand why this doesn't work, i am trying to retrieve whatever comes after "offer" in the specified url and then display it but when i click on the Offer button on android screen nothing happens. Please help if you could. I have the internet permission in manifest.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
public class LoggedIn extends Activity {
AlertDialog alertDialogStores;
ObjectItem[] ObjectItemData = new ObjectItem[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logged_in);
// a button to show the pop up with a list view
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShowPopUp:
LoaderTask task = new LoaderTask();
task.execute();
break;
}
}
};
findViewById(R.id.buttonShowPopUp).setOnClickListener(handler);
}
class LoaderTask extends AsyncTask<Void , Void ,String>{
ProgressDialog progressDialog ;
public LoaderTask(){
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading app data...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
showPopUp(result);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
public void showPopUp(String result){
try{
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i <= 5 ; i++){
JSONObject o = jsonArray.getJSONObject(i);
String http_response = o.getString("offer");
System.out.println("test "+http_response);
//ObjectItemData[i] = new ObjectItem(o);
ObjectItemData[0] = new ObjectItem(http_response);
ObjectItemData[1] = new ObjectItem(http_response);
ObjectItemData[2] = new ObjectItem(http_response);
ObjectItemData[3] = new ObjectItem(http_response);
ObjectItemData[4] = new ObjectItem(http_response);
// adapter instance
ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, ObjectItemData);
// create a new ListView, set the adapter and item click listener
ListView listViewItems = new ListView(this);
listViewItems.setAdapter(adapter);
listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
// put the ListView in the pop up
alertDialogStores = new AlertDialog.Builder(LoggedIn.this)
.setView(listViewItems)
.setTitle("Offers")
.show();
}
} catch(Exception e){e.printStackTrace();}
finally{System.out.println("Success");
}
}
}

class LoaderTask extends AsyncTask<Void , Void ,String>{
ProgressDialog progressDialog ;
public LoaderTask(){
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading app data...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
showPopUp(result);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
public void showPopUp(String result){
try{
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i < jsonArray.length() ; i++){
JSONObject o = jsonArray.getJSONObject(i);
String http_response = o.getString("offer");
System.out.println("test "+http_response);
ObjectItemData[i] = new ObjectItem(http_response);
}
//and populate your listview here
} catch(Exception e){e.printStackTrace();}
finally{System.out.println("Success");
}
}
and call this to do task
new LoaderTask().execute();

Related

How To Change this HTTP request to HttpUrlConnection

Since org.appache is deprecated in Android 5.1.1 , and they suggest to use HttpUrlConnection .
Could you help me to change my code this , with valid HttUrlConnection command (im new in Android)
package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.43.13:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
Thanks
Also , getASCIIContentFromEntity(HttpEntity entity) seems to be deprecated to !
EDIT : This is what i have changed in my code .
protected String doInBackground(Void... params) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.43.13:8000/api/horaire.json");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
But what about the "LongRunningGetIO extends AsyncTask " method ?
a HttpGet request without setting anything (like an Accept: application/json header, choosing an encoding, ...) should be fairly equivalent to this:
#Override
protected String doInBackground(Void... params) {
return get("http://192.168.43.13:8000/api/horaire.json");
}
private String get(String urlString) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
Reader reader = new InputStreamReader(urlConnection.getInputStream());
try {
StringWriter writer = new StringWriter();
char[] cbuf = new char[8192];
int read;
while ((read = reader.read(cbuf)) != -1) {
writer.write(cbuf, 0, read);
}
return writer.toString();
} finally {
reader.close();
}
} catch (Exception e) {
return e.getMessage();
}
}
Try This
#Override
protected String doInBackground(Void... params) {
StringBuffer response_string = new StringBuffer();
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
OutputStream os = con.getOutputStream();
os.write(params.toString().getBytes("UTF-8"));
os.close();
int responseCode = con.getResponseCode();
System.out.println("PostParseURL "+url);
System.out.println("PostParseCODE " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response_string.append(inputLine);
}
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response_string.toString();
}
and yes there are no need to getASCIIContentFromEntity method and here params are the Your JSONObject request

image upload to server of php error come in response = httpclient.execute(httppost);

i was make two file one is mainActivity and second is MultipartEntity
i post both file
MainActivity.java
package com.example.picupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button mTakePhoto;
private ImageView mImageView;
private static final String TAG = "upload";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.take_photo);
mImageView = (ImageView) findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(this);
}
#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 void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch (id) {
case R.id.take_photo:
takePhoto();
break;
}
}
private void takePhoto() {
// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
// startActivityForResult(intent, 0);
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.i(TAG, "onActivityResult: " + this);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
setPic();
// Bitmap bitmap = (Bitmap) data.getExtras().get("data");
// if (bitmap != null) {
// mImageView.setImageBitmap(bitmap);
// try {
// sendPhoto(bitmap);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
}
private void sendPhoto(Bitmap bitmap) throws Exception {
new UploadTask().execute(bitmap);
}
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
setProgress(0);
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume: " + this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
/**
* http://developer.android.com/training/camera/photobasics.html
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/picupload";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i(TAG, "photo path = " + mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
mImageView.setImageBitmap(rotatedBMP);
try {
sendPhoto(rotatedBMP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MultipartEntity.java
package com.example.picupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
saveimage.php
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "upload/" . $_FILES['myFile']['name']);
echo 'successful';
}
?>
geting error in
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please help me to solve..
working for me and please try to different network like wifi or mobile data
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
} } catch (ClientProtocolException e) {
responseString = e.toString(); } catch (IOException e) {
responseString = e.toString(); } return responseString;
Hey you can use this method for sending image to server
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public static JSONObject sendJSONDataWithImage() {
String Content = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.8.84:8003/savetofile.php");
File file = new File(yourFilePathwithfileName);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("UTF-8");
int size = (int) file.length();
byte[] bytes = new byte[size];
ByteArrayBody bab = null;
try {
BufferedInputStream buf = new BufferedInputStream(
new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
bab = new ByteArrayBody(bytes, yourFilePathwithfileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// reqEntity.addPart("user_id", new StringBody(otherParameter,chars));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
reqEntity.addPart("myFile", bab);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response;
try {
response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
json = s.toString();
System.out.println("Response.............: " + json);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
Log.e("add emp with img Response", "> " + json.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Please try this code:
package com.secondhandbooks.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
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.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.secondhandbooks.util.ConvertStreamIntoString;
import com.secondhandbooks.util.SaveImageIntoDrawable;
public abstract class BaseAsync_Post extends AsyncTask<String, String, InputStream>
{
Context context ;
private HttpPost httppost;
String url ;
Dictionary<String, String> dictionary ;
public BaseAsync_Post(String url , Dictionary<String, String> dictionary, Context context) {
this.url = url ;
this.dictionary = dictionary;
this.context = context ;
Enumeration<String> enumeration = dictionary.keys() ;
showLogs("constructor") ;
while ( enumeration.hasMoreElements() )
{
showLogs( enumeration.nextElement() ) ;
}
}
#Override
abstract protected void onPreExecute() ;
#Override
abstract protected void onPostExecute(InputStream result) ;
#Override
protected InputStream doInBackground(String... params) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
InputStream is = null;
HttpClient httpclient = new DefaultHttpClient();
httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(50);
Enumeration<String> enumeration = dictionary.keys() ;
while ( enumeration.hasMoreElements() )
{
String key = enumeration.nextElement() ;
if ( key.equals("file") )
{
final File file = new File(SaveImageIntoDrawable.savedImagePath);
if ( file.isFile() )
{
showLogs("is file");
}
else
{
showLogs("no-file");
}
FileBody fb = new FileBody(file);
entity.addPart(key, fb);
}
else
{
entity.addPart(key, new StringBody(dictionary.get(key)));
}
}
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity1);
is = bufHttpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
showLogs("ClientProtocolException");
} catch (IOException e) {
e.printStackTrace();
showLogs("IOException");
}
return is;
}
public String getString(JSONObject json, String TAG) {
String returnParseData = "";
try {
Object aObj = json.get(TAG);
if (aObj instanceof Boolean) {
returnParseData = Boolean.toString(json.getBoolean(TAG));
} else if (aObj instanceof Integer) {
returnParseData = Integer.toString(json.getInt(TAG));
} else if (aObj instanceof String) {
returnParseData = json.getString(TAG);
} else {
returnParseData = json.getString(TAG);
}
} catch (Exception err) {
err.printStackTrace();
returnParseData = "";
}
return returnParseData;
}
public String getIntintoString(JSONObject json, String TAG) {
int returnParseData = -1;
try {
returnParseData = json.getInt(TAG) ;
} catch (Exception err) {
err.printStackTrace();
returnParseData = -1;
}
return Integer.toString(returnParseData) ;
}
public void showLogs ( String msg )
{
Log.e("HTTP-POST", msg) ;
}
}
Try this simple code in your android, it works for me,
String url = "";// URL where image has to be uploaded
String fileName = ""; //path of file to be uploaded
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent = new FiSystem.out.println("hello");
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Hope this helps you with your problem...!!!!!

Send http post from android

I have a server made in python that reads the querystring-message and stores it in a sqlite database, and then displays the content.
Now I want to send the message from a android application. This is my code so far.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button send;
TextView display;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button)findViewById(R.id.button1);
display = (TextView)findViewById(R.id.editText1);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
post();
}
catch(Exception e)
{
display.setText("Det sket sig");
}
}
public void post() throws UnsupportedEncodingException
{
message = display.getText().toString();
String data = URLEncoder.encode("?message", "UTF-8")
+ "=" + URLEncoder.encode(message, "UTF-8");
String text = "";
BufferedReader reader=null;
try
{
URL url = new URL("http:homepage.net");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception e)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
display.setText(text);
}
});
}
#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;
}
}
This is not functioning as per the expectations. What am i doing wrong here?
for network related operation you have to use asynctask or thread other wise you wil get NetworkOnMainThread Exception.
refer here
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Use following AsyncTask to make server request:
public class RestServiceTask extends AsyncTask<String, Void, String> {
private String errorMessage;
public RestServiceTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[1];
String method = params[2];
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
HttpConnectionParams.setSoTimeout(httpParameters, 60000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpUriRequest request;
try {
if (method.equals("get")) {
request = new HttpGet(url);
} else {
request = new HttpPost(url);
if (params.length > 0 && params[0] != null) {
StringEntity entity = new StringEntity(params[0]);
((HttpPost) request).setEntity(entity);
Crashlytics.log(Log.INFO, "Request", params[0]);
}
((HttpPost) request).setHeader("Content-Type",
"application/json");
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String json = convertStreamToString(entity.getContent());
Crashlytics.log(Log.INFO, "Response", json);
return json;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//process your result
}
public String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
}
Use it by:
new RestServiceTask().execute("<json string>",url,method);//method can be get,post
try this simple example if you have any doubt follow this links:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://codeoncloud.blogspot.in/2012/07/android-php-web-service-client.html,http://sampleprogramz.com/android/singlewebservicecall.php
You should change the title of your question, there is no such thing as queryString in a POST. Query String parameters only gets added in a GET, and in POST you pass data in the body of the request.
Also, you could use this in combination with AsyncTask to solve your problem
EDIT: Also, Check here for more about GET and POST
Try this :
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(your website);
List<NameValuePair> entityParams = new ArrayList<NameValuePair>();
entityParams.add(new BasicNameValuePair("action", "postcomment"));
entityParams.add(new BasicNameValuePair("app_id", com.appbuilder.sdk.android.Statics.appId));
entityParams.add(new BasicNameValuePair("message", message1));
entityParams.add(new BasicNameValuePair("message2", message2));
httpPost.setEntity(new UrlEncodedFormEntity(entityParams, "utf-8"));
String resp = httpClient.execute(httpPost, new BasicResponseHandler());

Android reading php

I want to make an Android app that reads some data from a php page and put it into a textview.
I already tested it yesterday and it worked! but I dont know what i changed so today it wont work..
(I am sure that I dont used async tasks or something like this)
package com.example.test04;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private String url = "this is the url ";
private TextView textView;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById (R.id.textView2);
// runthread();
try{
textView.setText("");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line ="";
while ((line = rd.readLine()) != null) {
line = line.replace("\\n", "\n");
textView.append(line);
}
} catch (Exception e) {
Log.e("log_tag1234", "Error converting result === " + e.toString());
}
}}
after that I tried it with runOnUiThread but it also dont works
//
// private void runThread() {
//
// new Thread() {
// public void run() {
//
// try {
// runOnUiThread(new Runnable() {
//
// #Override
// public void run() {
// try{
// textView.setText("");
// HttpClient client = new DefaultHttpClient();
// HttpGet request = new HttpGet(url);
// HttpResponse response = client.execute(request);
//
// BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//
// String line ="";
// while ((line = rd.readLine()) != null) {
// line = line.replace("\\n", "\n");
// textView.append(line);
//
// }
//
// } catch (Exception e) {
// Log.e("log_tag1234", "Error converting result === " + e.toString());
// }
// }
// });
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// }.start();
// }
how can I fix it as easy as possible? why it doesnt work anymore?

JAVA ANDROID:Reading Php Json values, Eclipse dont see the error but it doesnt work

Reading Php Json values, Eclipse dont see the error but it doesnt work. Im becoming crazy because it must run, can you help me?
When i execute it nothing happens.
This is the java activity code:
package com.json.php;
import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONException;
import org.json.JSONObject;
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://iatek.eu/sys/getsms.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject obj = new JSONObject(jsonResult);
JSONArray jsonArray = obj.getJSONArray("posts");
/*Para hacer prueba accedo a un registro concreto en este caso el 3*/
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
/* para hacer pruebas lo he comentado
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject childJSONObject = jsonArray.getJSONObject(i);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
}*/
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
and here is the json code into iatek.eu/sys/getsms.php
{"posts":[{"cid":"11","username":"Livi","sms":"ag","fto":"","fcat":"cat"},{"cid":"10","username":"Sumone","sms":"","fto":"","fcat":""},{"cid":"9","username":"R2D2","sms":"dw","fto":"wd","fcat":"wd"},{"cid":"5","username":"Roy","sms":"sa","fto":"sa","fcat":"sa"},{"cid":"12","username":"Charles","sms":"ag","fto":"","fcat":"cat"},{"cid":"13","username":"Clarck","sms":"age","fto":"","fcat":"cat"}]}
can someone tell me where is the mistake?
thanks
You cannot run network operation on the main thread.
Use asyncTask instead.
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetSmsTask().execute("http://iatek.eu/sys/getsms.php");
}
private class GetSmsTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url[0]);
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity()
.getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
textView.setText(""+sms+"--" + username);
}
}
}
EDIT:
I just ran the code myslef, and I got this
09-13 13:33:59.315: W/System.err(14200): org.json.JSONException:
Unterminated object at character 7551 of {"posts":[{......
This means your JSON is invalid
http://pro.jsonlint.com/ paste your link there you will see the error.
To test that the code is working replace this
String jsonResult = inputStreamToString(response.getEntity()
.getContent()).toString();
with this:
String jsonResult = "{\"posts\":" +
"[{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
" {\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}, " +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}]}";
RESOLVED!!!! ALL ITS PERFECT
HERE IS THE CODE
THANK YOU VERY MUCH meda
package com.json.php;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONException;
import org.json.JSONObject;
import com.json.php.R;
public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetSmsTask().execute("http://YOURWEBSITE.eu/sys/getsms.php");
}
private class GetSmsTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
HttpResponse response = httpclient.execute(httppost);
/* String jsonResult = "{\"posts\":" + //FOR TESTS
"[{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
" {\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}, " +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}," +
"{\"cid\":\"11\",\"username\":\"Livi\",\"sms\":\"ag\",\"fto\":\"\",\"fcat\":\"cat\"}]}";
*/
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray;
try {
jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(3);
String username = childJSONObject.getString("username");
String sms = childJSONObject.getString("sms");
String fcat = childJSONObject.getString("fcat");
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(""+sms+"--" + username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Categories

Resources