-1

我在 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 会抛出以下错误消息: 错误信息

4

1 回答 1

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();
}
于 2013-08-20T19:45:13.200 回答