使用Volley android发送JSON数据

时间:2014-03-21 06:29:33

标签: android json android-fragments android-volley

我使用下面的代码将Jsondata发送到测试服务器,但我没有收到服务器的响应。 我越来越异常了。解决这个问题的任何方法? 如果我使用相同的代码将字符串发送到测试服务器它可以工作,但问题是Jsondata和Json数组。

public class MainActivity extends Activity 
{
AlertDialog alertDialog;
public EditText edit_text_Register_Username;
public EditText edit_text_password;
//SqlHandler sqlHandler;

String username,password;
String user,pass;

String result;
String fd_id;
String fd_name;
int value;

String asyn_response;
String status,contactid;

private static int RESULT_LOAD_IMAGE = 1;
ImageView mContent;
Bitmap mBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView upload = (ImageView) findViewById(R.id.imageView1);
     upload.setOnClickListener(new View.OnClickListener() 
     {
            @Override
            public void onClick(View arg0) 
            {
                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });

     ImageView upload1 = (ImageView) findViewById(R.id.imageView2);
     upload1.setOnClickListener(new View.OnClickListener() 
     {
            @Override
            public void onClick(View arg0) 
            {
                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
}

@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
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 
        {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imageView1);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }
    }


public void adminLogin(View view) 
{
     mContent = (ImageView) findViewById(R.id.imageView1);
     mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
     Canvas canvas = new Canvas(mBitmap);
     mContent.draw(canvas);

    edit_text_Register_Username = (EditText) findViewById(R.id.activity_login_username);
    edit_text_password = (EditText)findViewById(R.id.activity_login_password);

     String img = encodeTobase64(mBitmap);

    ReusableComponent.getInstance().edit_text_Register_Username = edit_text_Register_Username.getText().toString();
    ReusableComponent.getInstance().edit_text_password = edit_text_password.getText().toString();
    ReusableComponent.getInstance().mimage = img;

    String Signature = encodeTobase64(mBitmap);
    ReusableComponent.getInstance().mimage = Signature;

    JSONObject jsonObject = new JSONObject();
    try 
    {
        jsonObject.put("username", ReusableComponent.getInstance().edit_text_Register_Username);
        jsonObject.put("password", ReusableComponent.getInstance().edit_text_password);
        jsonObject.put("image", ReusableComponent.getInstance().mimage);
    }
    catch (JSONException e) 
    {
        e.printStackTrace();
    }
    postData(jsonObject);

}

private void postData(JSONObject jsonObject) 
{
    final TextView tv = (TextView) findViewById(R.id.respTxt);
    RequestQueue rq = Volley.newRequestQueue(this);

    JsonObjectRequest postReq = new JsonObjectRequest(Method.POST, "https://posttestserver.com/post.php", jsonObject, new Response.Listener<JSONObject>()
    {
        @Override
        public void onResponse(JSONObject response) 
        {
            tv.setText("working");              
        }
    },  new Response.ErrorListener() 
    {
        @Override
        public void onErrorResponse(VolleyError error) 
        {
            System.out.println("Error ["+error+"]");
            tv.setText("Failed");
        }
    });

    rq.add(postReq);
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException
{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;
}   

private String encodeTobase64(Bitmap image) 
{
    // RegistrationDetailToUpload.getInstance().mIsImageAttached = true;
    Bitmap immagex = image;
    if(image!=null)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

        Log.e("LOOK", imageEncoded);
        return imageEncoded;
    }
    else 
        return null;
}

}

1 个答案:

答案 0 :(得分:0)

尝试代码

public class MainActivity extends Activity 
{
AlertDialog alertDialog;
public EditText edit_text_Register_Username;
public EditText edit_text_password;
//SqlHandler sqlHandler;

String username,password;
String user,pass;

String result;
String fd_id;
String fd_name;
int value;

String asyn_response;
String status,contactid;

private static int RESULT_LOAD_IMAGE = 1;
ImageView mContent;
Bitmap mBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView upload = (ImageView) findViewById(R.id.imageView1);
     upload.setOnClickListener(new View.OnClickListener() 
     {
            @Override
            public void onClick(View arg0) 
            {
                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });

     ImageView upload1 = (ImageView) findViewById(R.id.imageView2);
     upload1.setOnClickListener(new View.OnClickListener() 
     {
            @Override
            public void onClick(View arg0) 
            {
                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
}

@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
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 
        {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imageView1);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }
    }


public void adminLogin(View view) 
{
     mContent = (ImageView) findViewById(R.id.imageView1);
     mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
     Canvas canvas = new Canvas(mBitmap);
     mContent.draw(canvas);

    edit_text_Register_Username = (EditText) findViewById(R.id.activity_login_username);
    edit_text_password = (EditText)findViewById(R.id.activity_login_password);

     String img = encodeTobase64(mBitmap);

    ReusableComponent.getInstance().edit_text_Register_Username = edit_text_Register_Username.getText().toString();
    ReusableComponent.getInstance().edit_text_password = edit_text_password.getText().toString();
    ReusableComponent.getInstance().mimage = img;

    String Signature = encodeTobase64(mBitmap);
    ReusableComponent.getInstance().mimage = Signature;

    JSONObject jsonObject = new JSONObject();
    try 
    {
        jsonObject.put("username", ReusableComponent.getInstance().edit_text_Register_Username);
        jsonObject.put("password", ReusableComponent.getInstance().edit_text_password);
        jsonObject.put("image", ReusableComponent.getInstance().mimage);
    }
    catch (JSONException e) 
    {
        e.printStackTrace();
    }
    postData(jsonObject);

}

private void postData(JSONObject jsonObject) 
{
    final TextView tv = (TextView) findViewById(R.id.respTxt);
    RequestQueue rq = Volley.newRequestQueue(this);

    JsonObjectRequest postReq = new JsonObjectRequest(Method.POST, "https://posttestserver.com/post.php", jsonObject.toString(), new Response.Listener<JSONObject>()
    {
        @Override
        public void onResponse(JSONObject response) 
        {
            tv.setText("working");              
        }
    },  new Response.ErrorListener() 
    {
        @Override
        public void onErrorResponse(VolleyError error) 
        {
            System.out.println("Error ["+error+"]");
            tv.setText("Failed");
        }
    });

    rq.add(postReq);
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException
{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;
}   

private String encodeTobase64(Bitmap image) 
{
    // RegistrationDetailToUpload.getInstance().mIsImageAttached = true;
    Bitmap immagex = image;
    if(image!=null)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

        Log.e("LOOK", imageEncoded);
        return imageEncoded;
    }
    else 
        return null;
}