想用子发送post方法参数给服务器

时间:2017-04-10 06:15:56

标签: android

我不知道将Post方法参数发送到服务器..我是android的新手......

我需要帮助..

下面是我在android中的代码

try
            {
                //param="SrvName=&MethodName=&Parameters=08 Mar 2017|07 Apr 2017|1|1|1|10112829|0|";

                url=new URL(u);

                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setDoInput(true);

                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Accept", "application/json");
                JSONObject param   = new JSONObject();

                param.put();

                OutputStream os = con.getOutputStream();
                //os.write(param.getBytes());
                os.flush();
                os.close();

                int responseCode = con.getResponseCode();

                if (responseCode == HttpURLConnection.HTTP_OK)
                {
                    InputStreamReader input=new InputStreamReader(con.getInputStream());

                    StringBuffer response = new StringBuffer();
                    int res=input.read();
                    while (res!=-1)
                    {
                        char ch=(char) res;
                        response.append(res);
                        res=input.read();
                    }
                    input.close();

                    System.out.println(response);
                }

            }catch (Exception e)
            {
                e.printStackTrace();
            }

我的帖子参数:

{
    "SrvName":"",
    "MethodName":"",
    "Parameters":"08 Mar 2017|07 Apr 2017|1|1|1|10112829|0|"
}

我想将此参数发送到服务器。

我必须使用任何子对象,因为我想使用json发送此参数。

2 个答案:

答案 0 :(得分:1)

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("foo1", "test");
        jsonObject.accumulate("foo2", "test2");

        // 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());
    }

答案 1 :(得分:0)

HTTP方法应该使用AsyncTask执行,onPreExecute有几种方法需要覆盖。 doInBackgroundonPostExecute@Override protected String doInBackground(Void... params) { // your variables ... JSONObject user_info = new JSONObject(); try { user_info.put("USER_NAME", name); user_info.put("USER_PWD", pass); Log.d("user_info", user_info.toString()); } catch (Exception ex) { Log.d("sending userinfo", "error in creating json object"); return dta; } HttpClient client = new DefaultHttpClient();//init client HttpResponse response = null; // Send Data Using Post Method try { HttpPost post = new HttpPost(your_url); StringEntity en = new StringEntity(user_info.toString()); //build data to be sent en.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(en); response = client.execute(post); if (response == null) { Log.e("error in response", "server not respond"); } else { Log.d("msg", "send data "); // now you got the response...parse it InputStream input = response.getEntity().getContent(); // and others coders... } 。发送帖子值应如下所示:

{{1}}