可以使用GET请求将json数据发送到Web服务吗?

时间:2015-07-17 09:19:32

标签: php android json web-services httpurlconnection

我想使用 GET 请求将包含登录信息的json数据发送到webservice。我现在正在做的是以下内容,

public JSONObject getJsonData(String url) {

        StringBuilder stringBuilder = new StringBuilder();
        JSONObject jsonObject = new JSONObject();
        JsonObject jsonSend = new JsonObject();
        jsonSend.addProperty("email","email@gmail.com");
        jsonSend.addProperty("password","*********");
        HttpURLConnection conn = null;
        try {
            URL url1 = new URL(url.toString());

            conn = (HttpURLConnection) url1
                    .openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setDoInput (true);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.connect();
            OutputStream out = null;
            out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(jsonSend.toString());
            Log.e("jsondata", jsonSend.toString());
            writer.close();
            out.close();
            conn.getResponseCode();
            InputStreamReader in = new InputStreamReader(
                    conn.getInputStream());

            int b;
            while ((b = in.read()) != -1) {
                stringBuilder.append((char) b);
            }
            try {
                Log.e("stringbuilder",stringBuilder.toString());
                jsonObject = new JSONObject(stringBuilder.toString());
            } catch (JSONException je) {
                Toast.makeText(this, "Error while creating json", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
//            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            try {
//                Toast.makeText(getApplicationContext()," code", Toast.LENGTH_SHORT).show();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        finally {
            conn.disconnect();
        }
        return jsonObject;
    }

即使我将请求方法指定为GET,它也试图在webservice中插入数据。 webservice具有 php 代码,如果用户凭据有效且接受GET请求,则该代码将接受json数据并返回json数据。请让我知道如何解决这个问题。感谢..

1 个答案:

答案 0 :(得分:0)

您无法在get()请求类型中定义内容类型。所以你不能在get请求中发送一个json。由于您可以在get请求中发送标头但在标头中无法发送json文件。