使用JSON将数据从Android应用程序发送到服务器

时间:2015-06-25 05:41:16

标签: android json http-post

我正在尝试从android应用程序在本地服务器中插入数据。我只是在测试我的应用程序的post方法。当我发送数据Testing Server显示这些数据但我在ADD_TASK本地服务器上测试我的应用程序时,它不会显示数据。可能我的应用程序不是以JSON Arrary格式发送数据。我正在遵循here中的相同代码。我编辑的代码用于访问我的本地服务器,如下所示。

@Override
public void onClick(View view) {

    switch(view.getId()){
        case R.id.btnPost:
            if(!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread
            new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
            break;
    }

}

public static String POST(String url, Person person){
    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 = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("task_title", person.getName());
        jsonObject.accumulate("task_details", person.getCountry());
        jsonObject.accumulate("ma_priority_id", person.getTwitter());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

此处此代码不会生成任何显示Toast Message Data Sent!的错误消息。 谁能告诉我解决方案?非常感谢您的及时回复。

3 个答案:

答案 0 :(得分:0)

尝试此功能

 public String request(String url, List<NameValuePair> nameValuePairs) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        // httpPost.setHeader("encytype", "multipart/form-data");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
        httpPost.setEntity(entity);

        HttpResponse httpResponse = httpClient.execute(httpPost);

        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");
        }
        reader.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Buffer Error" + "Error converting result " + e.toString());
    }

    return json;
}

答案 1 :(得分:0)

虽然不是一个正确的答案,你可以尝试一下,它是工作代码,它使用建议的HttpUrlConnection:

public class AnalyticsTest {
   ...
   @Before
   protected setUp() {
     analytics = new Analytics();
     analyticsSpy = spy(analytics);
     doNothing().when(analyticsSpy).startFlurry(any(Context.class), anyString());
   }
   ...
}

在php方面:

public static String postJSON(String myurl, JSONArray jarr) throws IOException {
        StringBuffer response = null;
        try {
            JSONObject parameters = new JSONObject();
            parameters.put("phoneType", "Android");
            parameters.put("jsonArray", jarr);
            parameters.put("key", "testkey");
            parameters.put("mail", "xyz@gmail.com");

            URL url = new URL(myurl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            System.out.println("params.tostring" + parameters.toString());

            writer.close();
            out.close();

            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println("Response in universal: " + response.toString());
        } catch (Exception exception) {
            System.out.println("Exception: " + exception);
        }

        return response.toString();
    }

答案 2 :(得分:0)

我建议您将此项目用作库:

https://github.com/matessoftwaresolutions/AndroidHttpRestService

这非常简单,我将它用于我的所有项目!它正在不断改进......

Asap(也许是本周)我会进行更新以使其适应Android Studio ...

我希望它有所帮助!!