使用HttpURLConnection而不是HttpPost

时间:2015-05-06 06:25:51

标签: java android http-post httpurlconnection

我有一个用java编写的Android应用程序代码。通过使用HttpPost和DefaultHttpClient库。目前,我正在重新编码它以使用HttpURLConnection替换HttpPost和DefaultHttpClient库,因为DefaultHttpClient已被删除。 我已经为我的一个项目完成了它,并且它有效。

但是在当前项目中,在使用HttpURLConnection而不是DefaultHttpClient时,我没有从webservice获得相同的响应。请问我在哪里错误地帮助我吗?

这是旧代码:

<!DOCTYPE html>
<html>
<head>

    <title>Typography</title>

    <script type="text/javascript" src="bower_components/angular-latest/src/Angular.js"></script>
    <script type="text/javascript" src="js/popup.js"></script>

</head>
<link rel="stylesheet" type="text/css" href="css/core.css">

<body ng-app="" ng-csp>
<h1>Typography</h1>
<div class="viewport">

    <form>
        <label for="baseline">Baseline</label>

        <div class="row clear"> 
            <input type="range" name="baselineRange" id="baselineRange" min="0" max="144" step="1"  />
            <input type="input" name="baseline" id="baseline"/>
        </div>

        <label for="offset">Baseline offset</label>
        <input type="text" name="offset" id="offset" />
        <button type="submit" id="send">Generate</button>

    </form>

    <p>Typography was created by <a href="//twitter.com/simpelism">Joel Sanden</a></p>
</div>
</body>
</html>

这是我的新代码

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
try {
 httpPost.setEntity(new StringEntity(postParameter));
} catch (Exception e) {
 e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);

代码运行时没有任何错误,但是webservice没有给出与旧代码相同的响应。

2 个答案:

答案 0 :(得分:1)

您没有获得输入流,请尝试下面的代码

         try {

                String postParameter = "Param1=" + Value1 + "&Param2="+ Value2+ "&Param3="+Value3;
                URL url = new URL(UrlStr);
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Accept",
                        "application/json");
                urlConnection.setRequestProperty("Content-Type",
                        "application/json");// setting your headers its a json in my case set your appropriate header

                urlConnection.setDoOutput(true);
                urlConnection.connect();// setting your connection

                OutputStream os = null;
                os = new BufferedOutputStream(
                urlConnection.getOutputStream());
                os.write(postParameter.toString().getBytes());
                os.flush();// writing your data which you post


                StringBuffer buffer = new StringBuffer();
                InputStream is = urlConnection.getInputStream();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                String line = null;
                while ((line = br.readLine()) != null)
                    buffer.append(line + "\r\n");
                     // reading your response 

                is.close();
                urlConnection.disconnect();// close your connection
                return buffer.toString();

            } catch (Exception e) {
            }

答案 1 :(得分:0)

试试这个

List nameValuePairs = new ArrayList(3);
            nameValuePairs.add(new BasicNameValuePair("Param1", value1));
            nameValuePairs.add(new BasicNameValuePair("Param2", value2));
            nameValuePairs.add(new BasicNameValuePair("Param3", value3));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);

OutputStream post = request.getOutputStream();
            entity.writeTo(post);
            post.flush();