2015-10-07 4 views
0

Как я могу помещать everythig в объект json?android отправить pic httppost с json-объектом

Я отправить ПИК на мой сервер, но сервер ответ с 422, потому что он хочет объект JSON как это:

parameters: {"spot": 
        {"description"=>"descriptionblabla", "title"=>"titleblabla" ..... , "photos_attributes" => {"0"=> "ref"=> thefile} }} 

и я посылаю это:

Parameters: {"title"=>"titlebla", "description"=>"descriptionbla"} 

апи лексема найдено 1075, user_id: 2189 Завершена 422 Unprocessable Entity в 44.5ms (Просмотров: 0.5мс | ActiveRecord: 21.6ms)

String token2= mPreferences.getString("auth_token",""); 

       // open a URL connection to the Servlet 
       fileInputStream = new FileInputStream(sourceFile); 
       URL url = new URL(upLoadServerUri); 

       // Open a HTTP connection to the URL 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setDoInput(true); // Allow Inputs 
       conn.setDoOutput(true); // Allow Outputs 
       conn.setUseCaches(false); // Don't use a Cached Copy 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Connection", "Keep-Alive"); 
       conn.setRequestProperty("ENCTYPE", "multipart/form-data"); 
       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
       conn.setRequestProperty("x-auth-token", token2); 
       conn.setRequestProperty("uploaded_file", sglimagepath); 



       dos = new DataOutputStream(conn.getOutputStream()); 

       dos.writeBytes(twoHyphens + boundary + lineEnd); 
       dos.writeBytes("Content-Disposition: form-data; name=\"title\"" + lineEnd); 
       dos.writeBytes(lineEnd); 
       dos.writeBytes("nuova foto3"); 
       dos.writeBytes(lineEnd); 
       dos.writeBytes(twoHyphens + boundary + lineEnd); 

       dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd); 
       dos.writeBytes(lineEnd); 
       dos.writeBytes("proviamoci2"); 
       dos.writeBytes(lineEnd); 
       dos.writeBytes(twoHyphens + boundary + lineEnd); 

       /*dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + sglimagepath +"\"" + lineEnd); 
       dos.writeBytes(lineEnd);*/ 

       dos.writeBytes(lineEnd); 


       // create a buffer of maximum size 
       bytesAvailable = fileInputStream.available(); 

       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       buffer = new byte[bufferSize]; 

       // read file and write it into form... 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

       while (bytesRead > 0) { 

        dos.write(buffer, 0, bufferSize); 
        bytesAvailable = fileInputStream.available(); 
        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
        bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

       } 

       // send multipart form data necesssary after file data... 
       dos.writeBytes(lineEnd); 
       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

       // Responses from the server (code and message) 
       serverResponseCode = conn.getResponseCode(); 
       String serverResponseMessage = conn.getResponseMessage(); 

Я исправил мой вопрос, я написал здесь, как я сделал: https://stackoverflow.com/questions/33352017/android-send-file-httppost-to-server

+0

Вы не отправляете «Параметры». Вы также не отправляете JSON. Вы также не отправляете картинку. Что означает 442? – greenapps

+0

означает, что «Unprocessable Entity» походит на то, что он получает все, как указано выше, но он хочет, чтобы объект json назывался «spot» и после всех параметров ... Весь журнал: api token найден 1081, user_id: 2189 Завершено 422 Непроцессная организация в 46.4ms (Просмотров: 0.4ms | ActiveRecord: 25.7ms) ..... Я не знаю, как я могу поставить перед объектом и после всех параметров ..... – Alexiscanny

+0

В коде отсутствует json. Поэтому начните с создания json-объекта или json-массива. После этого вы создаете текст json и отправляете это. – greenapps

ответ

1

Как, как вы сказали @greenapps не было никакого Json, я все еще имеющие проблемы, но это еще один сейчас, так что я хотел написать, как я установил проблема относительно ошибки, которая у меня была (ошибка 422). Я отправлю код ниже:

String token2= mPreferences.getString("auth_token",""); 

       // open a URL connection to the Servlet 
       fileInputStream = new FileInputStream(sourceFile); 
       URL url = new URL(upLoadServerUri); 

       //create json object 
       try { 
        spot.put("title", "titolo1"); 
        spot.put("latitude", "1"); 
        spot.put("longitude", "1"); 
        spot.put("address", "antani"); 
        spot.put("country", "IT"); 
        spot.put("shot_level", "pro"); 
        spot.put("photo_attributes",photo_attributes); 
         photo_attributes.put("0",attributes); 
          attributes.put("description","Nesciunt dignissimos qui non. Beatae optio eveniet quis.."); 
          attributes.put("our_policies","1"); 
         /*photo_attributes.put("1",attributes); 
          attributes.put("description","Nesciunt dignissimos qui non. Beatae optio eveniet quis.."); 
          attributes.put("our_policies","2");*/ 

       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       //Convert json to hashmap 
       HashMap<String, String> attributesmap = new HashMap<String, String>(); 
       JSONObject attributesObject = new JSONObject(attributes.toString()); 

       HashMap<String, String> photo_attributesmap = new HashMap<String, String>(); 
       JSONObject photo_attributesObject = new JSONObject(photo_attributes.toString()); 

       HashMap<String, String> map = new HashMap<String, String>(); 
       JSONObject spotjObject = new JSONObject(spot.toString()); 


       Iterator<?> keys = spotjObject.keys(); 
       Iterator<?> keys2 = photo_attributesObject.keys(); 
       Iterator<?> keys3 = attributesObject.keys(); 

       while(keys3.hasNext()){ 
        String key3 = (String)keys3.next(); 
        String value3 = attributesObject.getString(key3); 
        attributesmap.put(key3, value3); 
       } 
       while(keys2.hasNext()){ 
        String key2 = (String)keys2.next(); 
        String value2 = photo_attributesObject.getString(key2); 
        photo_attributesmap.put(key2, value2); 
       } 
       while(keys.hasNext()){ 
        String key = (String)keys.next(); 
        String value = spotjObject.getString(key); 
        map.put(key, value); 
       } 


       File file = new File(sglimagepath); 
       try { 
        client = new DefaultHttpClient(); 
        String postURL = upLoadServerUri; 
        post = new HttpPost(postURL); 

        //FileBody fileBody = new FileBody(file); 
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

        ContentBody con =new StringBody(map.toString()); 
        //ContentBody con2 =new StringBody(photo_attributesmap.toString()); 
        //ContentBody con3 =new StringBody(con.toString()+con2.toString()); 
        //post.setEntity(se); 
        reqEntity.addPart("spot", con); 
        //reqEntity.addPart("image", fileBody); 

        post.setHeader("x-auth-token", token2); 
        post.setEntity(reqEntity); 
        HttpResponse response2 = client.execute(post); 
        HttpEntity resEntity = response2.getEntity(); 
        if (resEntity != null) { 
         Log.i("RESPONSE", EntityUtils.toString(resEntity)); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
Смежные вопросы