代码入下:
         /**
 * 提交信息
 * 
 * @param s
 *            服务器
 * @param param
 *            提交的数据
 * @throws Exception
 */
private void submit(Server s, Map param) throws Exception {

HttpURLConnection conn = (HttpURLConnection) new URL("http://" + s.ip
+ ":" + s.port).openConnection();
String authentication = (new sun.misc.BASE64Encoder())
.encode((s.adminName + ":" + s.adminPassword).getBytes());
conn.setRequestProperty("Authorization", "Basic " + authentication);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
throw new Exception("连接失败!");

 conn = (HttpURLConnection) new URL("http", s.ip,
Integer.parseInt(s.port), "/account").openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authentication); Iterator it = param.keySet().iterator();
String p = "";
while (it.hasNext()) {
String key = (String) it.next();
p += key + "=" + param.get(key);
if (it.hasNext())
p += "&";
}
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(p);
out.write("\r\n");
out.flush();
out.close(); BufferedReader br = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
出现的错误:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://127.0.0.1:88/account
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1149)
at tool.proxy.UserManage.submit(UserManage.java:177)
at tool.proxy.UserManage.main(UserManage.java:238) while (br.ready())
System.out.println(br.readLine());
}

解决方案 »

  1.   

    http://community.csdn.net/Expert/topic/4855/4855437.xml?temp=.1530878
    开两个贴,总共是110分.
      

  2.   

    我监听了n多天网络,还是没搞定顺便说一下,认证是basic
      

  3.   

    重新说明一下,我想用java的http连接做 basic认证 + Post数据,该怎么做?谁做这片比较多,我找了N家论坛没人解决!
      

  4.   


    ...;conn.disconnect();
    conn = (HttpURLConnection) new URL("http", s.ip, Integer.parseInt(s.port), "/account").openConnection();...;BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sbInfo = new StringBuffer();
    if(br.ready()){
        String newLine = "\r\n";
        String readInfo = null;
        while((readInfo=br.readLine())!=null) {
            sbInfo.append(readInfo);
            sbInfo.append(newLine);
        }
    }
    System.out.println("Response message: \r\n" + sbInfo.toString());
      

  5.   

    嗯,这样在 没basic认证 上是可以的.谢谢楼上的回复和朋友的支持.
      

  6.   

    没有啊,只认证一次,下面是认证部分代码:String authentication = (new sun.misc.BASE64Encoder()).encode((s.adminName + ":" + s.adminPassword).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + authentication);
      

  7.   

    ...;
    conn.setRequestProperty("Authorization", "Basic " + authentication); // 1
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
    throw new Exception("连接失败!");...;
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Basic " + authentication);// 2
      

  8.   

    谢谢yaray(雅睿,生活在别处) 的回复.嗯,可能贴错了,但是去掉也不行.现在程序已经改成这样了,参数都是用嗅探器拦截IE上的,这样也试过,也是一样报.
    java.io.IOException: Server returned HTTP response code: 401 for URL: http://127.0.0.1:88/account
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1149)
    at tool.proxy.UserManage.submit(UserManage.java:177)
    at tool.proxy.UserManage.main(UserManage.java:238)
    /**
     * 提交信息
     * 
     * @param s
     *            服务器
     * @param param
     *            提交的数据
     * @throws Exception
     */
    private void submit(Server s, Map param) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) new URL("http", s.ip,
    Integer.parseInt(s.port), "/account").openConnection();
    conn.setRequestMethod("POST");
    conn
    .setRequestProperty(
    "Accept",
    "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
    conn.setRequestProperty("Accept-Language", "zh-cn");
    conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
    //  conn.setRequestProperty("Content-Length",
    //  String.valueOf(p.length()));
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn
    .setRequestProperty(
    "User-Agent",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); conn.setDoInput(true);
    conn.setDoOutput(true);
    // conn.setUseCaches(false);
    String authentication = (new sun.misc.BASE64Encoder())
    .encode((s.adminName + ":" + s.adminPassword).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + authentication);

    Iterator it = param.keySet().iterator();
    String p = "";
    while (it.hasNext()) {
    String key = (String) it.next();
    p += key + "=" + param.get(key);
    if (it.hasNext())
    p += "&";
    }
    OutputStream os = conn.getOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeBytes(p);
    dos.flush();
    dos.close();

    System.err.println(conn.getResponseCode());
    //conn.connect();
    //conn.disconnect();
    }
      

  9.   

    httpclient版本:
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.PostMethod;public class Test { public static void main(String args[]) {
    try {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://user2:88/account");
    UsernamePasswordCredentials upc = new UsernamePasswordCredentials(
    "admin", "");
    client.getState().setCredentials(AuthScope.ANY, upc);
    post.setDoAuthentication(true); post.setParameter("delete", "-1");
    post.setParameter("userid", "0");
    post.setParameter("autodisable", "1");
    post.setParameter("username", "12");
    post.setParameter("password", "112");
    post.setParameter("enable", "1");
    post.setParameter("connection", "10");
    post.setParameter("bandwidth", "-1");
    post.setParameter("disabledate", "2006-07-03");
    post.setParameter("disabletime", "23:10:31"); NameValuePair[] data = { new NameValuePair("delete", "-1"),
    new NameValuePair("userid", "0"),
    new NameValuePair("autodisable", "1"),
    new NameValuePair("username", "12"),
    new NameValuePair("password", "112"),
    new NameValuePair("enable", "1"),
    new NameValuePair("connection", "10"),
    new NameValuePair("bandwidth", "-1"),
    new NameValuePair("disabledate", "2006-07-03"),
    new NameValuePair("disabletime", "23:10:31") };
    post.setRequestBody(data); int result = client.executeMethod(post); System.err.println(result);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }报错:java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:235)
    at org.apache.commons.httpclient.HttpParser.readRawLine(Unknown Source)
    at org.apache.commons.httpclient.HttpParser.readLine(Unknown Source)
    at org.apache.commons.httpclient.HttpConnection.readLine(Unknown Source)
    at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(Unknown Source)
    at org.apache.commons.httpclient.HttpMethodBase.readResponse(Unknown Source)
    at org.apache.commons.httpclient.HttpMethodBase.execute(Unknown Source)
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(Unknown Source)
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(Unknown Source)
    at org.apache.commons.httpclient.HttpClient.executeMethod(Unknown Source)
    at org.apache.commons.httpclient.HttpClient.executeMethod(Unknown Source)
    at Test.main(Test.java:41)
      

  10.   

    想用socket直接发,参照嗅探IE的结果来发.
      

  11.   

    http://user2:88/account这个地址用普通的数据提交方式时是否可以正常工作?
      

  12.   

    谢谢yaray(雅睿,生活在别处) 的提示,终于搞定了,哈哈.......结贴,还有20分,麻烦去回一下贴.
      

  13.   

    可以的,用IE可以.20分的贴在这边.
    http://community.csdn.net/Expert/topic/4855/4855437.xml?temp=.1530878
      

  14.   

    错误错在,delete是一个submit按钮,我是在servlet取出为-1的,实际上Http监听上为delete=%C9%BE%B3%FD,URLDecoder.decode("%C9%BE%B3%FD", "UTF-8")为???,太粗心了,监听好几次都没仔细看.最终代码(socket直接发),测试通过:import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.URLEncoder;public class Test { public static void main(String args[]) {
    try {
    String data = "userid=0&autodisable=1&delete=%C9%BE%B3%FD&username=12&password=1212&enable=1&connection=10&bandwidth=-1&disabledate=2006-03-07&disabletime=21%3A46%3A38"; String authentication = (new sun.misc.BASE64Encoder())
    .encode(("admin" + ":" + "").getBytes()); // Create a socket to the host
    String hostname = "user2";
    int port = 88;
    InetAddress addr = InetAddress.getByName(hostname);
    Socket socket = new Socket(addr, port); // Send header
    String path = "/account";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
    socket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.1\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Authorization: Basic " + authentication + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n"); // Send data
    wr.write(data);
    wr.flush();
    wr.close();
    socket.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }谢谢yaray(雅睿,生活在别处) 帮忙!