使用UrlFetchTransport在Google App Engine上执行GET / POST

时间:2014-03-02 20:21:39

标签: java google-app-engine post urlfetch

我在GAE上移植了一个Android应用。 该应用程序编译并发布登录表单以输入 密码保护的网站。 我正在使用UrlFetchTransport而不是DefaultHttpClient。 使用以下代码我可以毫无问题地获取网页:

    HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();

    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
    GenericUrl genericUrl = new GenericUrl(url);
    HttpRequest request = requestFactory.buildGetRequest(genericUrl);
    com.google.api.client.http.HttpHeaders httpHeaders = request.getHeaders();

    httpHeaders.setUserAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
    httpHeaders.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");



    String paginaRicevuta = request.execute().parseAsString();

我会使用以下内容尝试POST请求:

                UrlFetchTransport HTTP_TRANSPORT = new UrlFetchTransport();
                HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
                GenericUrl genericUrl = new GenericUrl("https://www.......");

                List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
                nvps.add(new BasicNameValuePair("ReturnUrl", ""));
                nvps.add(new BasicNameValuePair("userName", "username"));
                nvps.add(new BasicNameValuePair("password","password"));

                //HERE HOW DEFINE httpContent????                   
                HttpContent httpContent=null;

                final HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl,httpContent);
                postRequest.setContent(httpContent);
                postRequest.setFollowRedirects(true);
                HttpHeaders httpHeaders = postRequest.getHeaders();                 
                httpHeaders.setUserAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
                httpHeaders.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                httpHeaders.setContentType("application/x-www-form-urlencoded");
                postRequest.setHeaders(httpHeaders);
                String pagePost = postRequest.execute().parseAsString();

但我不知道如何格式化正确的POST请求? 谢谢你的帮助。

0 个答案:

没有答案