有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

参数不适用于ASP服务器的java HttpPost

我需要创建一个带有两个参数的HttpPost请求。我同意有很多例子,但我相信我已经完成了我的研究,但仍然没有从ASP服务器得到响应。我尝试了NameValuePair,但似乎无法获得响应页面。我猜这些参数没有添加到httpPost对象中

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://portal.sibt.nsw.edu.au/Default.asp");

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("userID", id.getText().toString()));
nameValuePair.add(new BasicNameValuePair("password", pword.getText().toString()));

post.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = client.execute(post);

String responseContent = EntityUtils.toString(response.getEntity());
Log.d("response to string", responseContent);

我再次获得登录页面,此代码返回NullPointerException:

String newURL = response.getFirstHeader("Location").getValue();

我做错了什么


共 (4) 个答案

  1. # 1 楼答案

    试着这样做:

    private static String urlAppendParams(String url, List<NameValuePair> lNameValuePairs) {
        if (lNameValuePairs != null) {
            List<NameValuePair> llParams = new LinkedList<NameValuePair>();
            for (NameValuePair nameValuePair : lNameValuePairs) {
                llParams.add(nameValuePair);
            }
    
            String sParams = URLEncodedUtils.format(llParams, "UTF-8");
            if (!url.endsWith("?")) {
                url += "?";
            }
            url += sParams;
        }
        return url;
    }
    
  2. # 2 楼答案

    你不用。NET网页,您必须创建。NET web服务,因为只有web服务具有post和get方法。您不请求网页。网页未收到您的消息和答复

  3. # 3 楼答案

    当您使用浏览器(https://portal.sibt.nsw.edu.au/Default.asp)到达主页时,服务器将打开会话(您可以使用网络检查器查看set cookie标头):

    Set-Cookie:ASPSESSIONIDQCCCQQCQ=HJMMOCFAFILCLNCJIMNBACIB; path=/
    

    您可能需要在POST登录之前对此页面发出GET请求。此外,您必须在HttpClient中启用cookie跟踪。我通常使用:

    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    final HttpGet get = new HttpGet("https://portal.sibt.nsw.edu.au/Default.asp");
    client.execute(get); //perform an initial GET to receive the session cookie
    
    //now do the post...
    HttpPost post = new HttpPost("https://portal.sibt.nsw.edu.au/Default.asp?Summit=OK");
    
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("hcUserID", id.getText().toString()));
    nameValuePair.add(new BasicNameValuePair("hcPassword", pword.getText().toString()));
    
    post.setEntity(new UrlEncodedFormEntity(nameValuePair));
    HttpResponse response = client.execute(post);
    
    //I should be logged in.... Lets get the an internal webpage
    get = new HttpGet("https://portal.sibt.nsw.edu.au/std_Alert.asp");
    client.execute(get);
    
    System.out.println(new String(get.getResponseBody()));
    

    由于我没有有效的用户/密码,因此无法尝试此解决方案

  4. # 4 楼答案

    我猜您只是错过了url末尾的?