简体   繁体   中英

HttpURLConnection method is always GET?

As the Android documents indicate, I've set setDoOutPut(true); so that the connection sends as POST . However, in the debugger when I check the HTTPURLConnection method member, it is always GET , even after setDoOutput(true) and even setRequestMethod("POST") . Am I somehow resetting it back to GET ?

URL url = new URL(serverAddr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod(verb);
urlConnection.setFixedLengthStreamingMode(postBody.getBytes().length);
//urlConnection.setRequestProperty("Content-Length", postBody.getBytes().toString());
urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

urlConnection.connect();

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(postBody.getBytes());
out.flush();

int responseCode = urlConnection.getResponseCode();
System.out.println("HTTPS RESPONSE CODE: " + responseCode);

out.close();

EDIT: This has got to be a bug...the debugger shows setDoOuput member variable clearly as false even when I'm setting it to true. It's not being set!

You need to use urlConnection.setDoInput(true); if you wish to use POST verb and send data with your request.

http://developer.android.com/reference/java/net/URLConnection.html#setDoInput(boolean)

It must be set before connection is established.

This is my working example:

    url = new URL(requestURL);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(15000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);


    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(postDataParams));

    writer.flush();
    writer.close();
    os.close();
    int responseCode=conn.getResponseCode();
    Map<String, List<String>> mp = conn.getHeaderFields();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line=br.readLine()) != null) {
            response+=line;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM