【问题标题】:Java HTTP-Request with POST-Data带有 POST 数据的 Java HTTP 请求
【发布时间】:2013-08-20 19:35:37
【问题描述】:

我在 java 中编写了以下代码,通过 POST-Variables 将一些数据发送到我网站的 PHP 文件,然后我想获取该网站的源代码。

public DatabaseRequest(String url, IDatabaseCallback db_cb)
        {
            this.db_cb = db_cb;
            site_url = url;
            client = new DefaultHttpClient();
            request = new HttpPost(site_url);
            responseHandler = new BasicResponseHandler();
            nameValuePairs = new ArrayList<NameValuePair>(0);
        }

        public void addParameter(List<NameValuePair> newNameValuePairs)
        {
            nameValuePairs = newNameValuePairs;
        }

        public void run()
        {
            db_cb.databaseFinish(getContent());
        }

        public String[] getContent()
        {

            String result = "";
            try {
                request.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
                result = client.execute(request, responseHandler);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] result_arr = result.trim().split("<br>");
            for (int i = 0; i < result_arr.length; i++)
            {
                result_arr[i] = result_arr[i].trim();
            }
            return result_arr;
        }

当我想运行这段代码时,eclipse 会抛出以下错误消息:

【问题讨论】:

  • 如何运行这段代码?

标签: java android http-request


【解决方案1】:

试试这个:

// executes the request and gets the response.
HttpResponse response = client.execute(httpPostRequest);
// get the status code--- 200 = Http.OK
int statusCode = response.getStatusLine().getStatusCode();

HttpEntity httpEntity = response.getEntity();
responseBody = httpEntity.getContent();    

if (statusCode = 200) {
    // process the responseBody. 
}
else{
    // there is some error in responsebody
}

编辑:处理UnsupportedEncodingException

在发出 HTTP 请求之前,您需要对 post 数据进行编码,以便将所有字符串数据转换为有效的 url 格式。

// Url Encoding the POST parameters
try {
    httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}

【讨论】:

  • 对于 responseBody 你可以使用 String responseBody = EntityUtils.toString(response.getEntity());
  • 这会引发不支持的编码错误 (uft-8)。我是否必须为我的 PHP 文件设置不同的编码类型?
  • 你能粘贴一下logcat吗?
猜你喜欢
  • 1970-01-01
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多