如何使用HttpUrl连接在android api 23中使用post发送名称对对象或内容值对象?

时间:2016-01-17 04:37:34

标签: android url httpurlconnection

//这是我尝试过的。 //我不知道如何附加inputurl和Content值并使用HttpURLConnection将其发送到服务器。

public JSONObject getJsonFromUrl(String inputurl,ContentValues values){

    // Making http Request

    try {
        URL url=new URL(inputurl);

        HttpURLConnection connection=(HttpURLConnection)url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");

        connection.setDoInput(true);

        connection.setDoOutput(true);

///请在此处插入代码,以便使用url附加值。             connection.connect();

        //
        inputStream=connection.getInputStream();

    }
    catch (java.net.MalformedURLException e1){
        e1.printStackTrace();
    }
    catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }


    try {
        BufferedReader reader=new BufferedReader(new    InputStreamReader(inputStream,"iso-8859-1"),8);
        reader.read(getPost)
        StringBuilder builder=new StringBuilder();
        String line=null;

        while ((line=reader.readLine() !=null){
            builder.append(line + "n");
        }

        inputStream.close();
        jsonString=inputStream.toString();
        Log.e("JSON", jsonString);
    }
    catch (Exception e){
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try to parse the string into json object
    try {
        jsonObject=new JSONObject(jsonString);

    }
    catch (JSONException e){
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jsonObject;

}

}

1 个答案:

答案 0 :(得分:1)

如果您想通过HttpUrlConnection实例将JSON对象发布到url,可以这样写。

    DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
    wr.writeBytes(jsonObject.toString());
    wr.flush();
    wr.close();
Where,

jsonObject is the json object which you would be posting to the URL 

整个代码可能看起来像这样

URL url = new URL("this would be your url where you want to POST");

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
// when you are posting do make sure you assign appropriate header
// In this case POST.

httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();

// like this you can create your JOSN object which you want to send
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("email", "dddd@gmail.com");
jsonObject.addProperty("password", "password");

// And this is how you will write to the URL
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();

Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));