简体   繁体   English

如何在Java中的HttpURLConnection中放置自定义请求位置

[英]How to put custom request location in HttpURLConnection in java

I created an HttpURLConnection object like this. 我创建了这样的HttpURLConnection对象。

URL urlObj = new URL(" http://www.example.com/login "); URL urlObj =新URL(“ http://www.example.com/login ”); HttpURLConnection conn; HttpURLConnection conn; conn = urlObj.openConnection(); conn = urlObj.openConnection(); conn.setRequestMethod("GET"); conn.setRequestMethod(“ GET”);

So when I request, it will go like this: 因此,当我请求时,它将如下所示:

GET http://www.example.com/login HTTP/1.1 GET http://www.example.com/login HTTP / 1.1

but I want to change the http://www.example.com/login to just /login. 但我想将http://www.example.com/login更改为/ login。 I mean like this: 我的意思是这样的:

GET /login HTTP/1.1 GET / login HTTP / 1.1

Is there any way to do that? 有什么办法吗?

Thanks 谢谢

PS: I checked the request form using a proxy server, it looked like: PS:我使用代理服务器检查了请求表,它看起来像:

GET http://example.com/login HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Host: example.com
Proxy-Connection: keep-alive

Code

package test;

import java.io.*;
import java.util.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.*;

public class UBConnection
{

    private List<String> cookies;
    private final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0";
    private int fileCounter = 0;

    public static void main(String[] args) throws Exception
    {
        System.setProperty("http.proxySet", "true");
        System.setProperty("http.proxyHost", "localhost");
        System.setProperty("http.proxyPort", "2121");
        UBConnection http = new UBConnection();
        http.login("gfhgfh", "fghfh");
    }

    public UBConnection() throws Exception
    {
        configSSL();
    }

    public static void configSSL() throws Exception
    {
        System.setProperty("https.protocols", "SSLv3");
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[]
        {
            new DefaultTrustManager()
        }, new SecureRandom());
        SSLContext.setDefault(ctx);
        CookieHandler.setDefault(new CookieManager());
    }

    public void login(String username, String password) throws Exception
    {
        String loginUrl = "http://www.example.com/login";
        CookieHandler.setDefault(new CookieManager());
        //String page = new String(send(true, loginUrl, "", true));
        String postParams = getFormParams(username, password);
        byte[] b = send(true, loginUrl, postParams, false);
    }

    private byte[] send(boolean isGet, String url, String postParams, boolean isSecure) throws Exception
    {
        if (postParams == null)
        {
            postParams = "";
        }
        URL urlObj = new URL(url);
        HttpURLConnection conn;
        if (isSecure == true)
        {
            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            conn = (HttpsURLConnection) urlObj.openConnection();
            ((HttpsURLConnection) conn).setSSLSocketFactory(sslsocketfactory);
        }
        else
        {
            conn = (HttpURLConnection) urlObj.openConnection();
        }
        if (isGet == true)
        {
            conn.setRequestMethod("GET");
        }
        else
        {
            conn.setRequestMethod("POST");
        }
        System.out.println("Aum: " + conn);
        conn.setUseCaches(false);
        conn.setRequestProperty("Host", urlObj.getHost());
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        conn.setRequestProperty("Referer", url);
        if (cookies != null)
        {
            for (String cookie : this.cookies)
            {
                conn.addRequestProperty("Cookie", cookie);
            }
        }
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        if (isGet == false)
        {
            conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
        }

        conn.setDoOutput(true);
        conn.setDoInput(true);

        if ((isGet == false) && (postParams != null))
        {
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(postParams);
            wr.flush();
            wr.close();
        }
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending " + (isGet == true ? "GET" : "POST") + " request to URL : " + url);
        if (isGet == false)
        {
            System.out.println("Post parameters : " + postParams);
        }
        System.out.println("Response Code : " + responseCode);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataInputStream din = new DataInputStream(conn.getInputStream());
        int i = 0;
        while (i != -1)
        {
            i = din.read();
            bos.write(i);
        }
        byte[] b = bos.toByteArray();
        putToFile(new String(b), "file" + fileCounter + ".htm");
        fileCounter++;
        return b;
    }

    public String getFormParams(String username, String password) throws UnsupportedEncodingException
    {
        return "auth=ldap&url=%5EU&user=" + username + "&pass=" + password + "&submit.x=66&submit.y=23";
    }

    public List<String> getCookies()
    {
        return cookies;
    }

    public void setCookies(List<String> cookies)
    {
        this.cookies = cookies;
    }

    public byte[] setPost(String url, String params, boolean https) throws Exception
    {
        return send(false, url, params, https);
    }

    public byte[] setGet(String url, String params, boolean https) throws Exception
    {
        return send(true, url, params, https);
    }

    private void putToFile(String data, String filename) throws Exception
    {
        System.out.println("Saving to file " + filename);
        FileWriter fw = new FileWriter(new File(filename));
        fw.write(data);
        fw.close();
    }
}

Proxy Server Code: 代理服务器代码:

package test;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleProxy
{

    public static void main(String arg[]) throws Exception
    {
        ServerSocket server = new ServerSocket(2121);
        System.out.println("Server Started on 2121\n--------------------------------------------------------");
        while (true)
        {
            Socket socket = server.accept();
            ClientConnection client = new ClientConnection(socket);
            client.start();
        }
    }
}

class ClientConnection extends Thread
{
    Socket clientCon;
    private String response = "HTTP/1.1 200 OK\n" +
"Date: Wed, 27 Nov 2013 04:47:00 GMT\n" +
"Server: Apache\n" +
"Pragma: no-cache\n" +
"Keep-Alive: timeout=2, max=32\n" +
"Connection: Keep-Alive\n" +
"Content-Type: text/html; charset=UTF-8";

    public ClientConnection(Socket socket)
    {
        clientCon = socket;
    }

    public void run()
    {
        try
        {
            DataInputStream din = new DataInputStream(clientCon.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int i = 0;
            while (din.available() > 0)
            {
                i = din.read();
                bos.write(i);
            }
            String request = new String(bos.toByteArray());
            System.out.println(request);
            System.out.println("--------------------------------------------------------");
            clientCon.getOutputStream().write(response.getBytes());
            clientCon.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

The actual request will still be made using: 实际的请求仍将使用:

GET /login HTTP/1.1
Host: www.example.com
...

The host header will be set to www.example.com 主机标头将设置为www.example.com

URL.openConnection

will establish a connection to www.example.com using a raw Socket 将使用原始Socket建立与www.example.com的连接

If your request is going through a proxy server, the file path will be set to the entire URL(in your case http://www.example.com/login ). 如果您的请求通过代理服务器,则文件路径将设置为整个URL(在您的情况下为http://www.example.com/login )。 Configuring to use a proxy is the same as using the overloaded form of the URL constructor with 4 arguments: protocol, host, port, path. 配置为使用代理与使用URL构造函数的重载形式(带有4个参数)相同:协议,主机,端口,路径。

URL url = new URL("http", proxyHost, proxyPort, "http://www.example.com/login");

Without a proxy: 没有代理:

URL url = new URL("http", "www.example.com", 80, "/login");

So when I request, it will go like this: 因此,当我请求时,它将如下所示:

GET http://www.example.com/login HTTP/1.1

No it won't. 不,不会。

but I want to change the http://www.example.com/login to just /login. 但我想将http://www.example.com/login更改为/ login。 I mean like this: 我的意思是这样的:

GET /login HTTP/1.1

That's how it will go. 这样便可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM