通过Java发送HTTP请求GET/POST表单?

时间:2022-08-22 19:30:13

So I have this piece of code, and I got it to work, and now it basically allows me to send http post and get requests to almost any external website I want UNLESS the elements don't contain a name attribute. Here's an example:

所以我有这段代码,我让它工作,现在它基本上允许我发送http post请求几乎所有我想要的外部网站,除非元素不包含name属性。这里有一个例子:

This is the Java code:

这是Java代码:

    public static String sendPostRequest(String url) {

    StringBuffer sb = null;

    try {

        String data = URLEncoder.encode("user", "UTF-8") + "="
                + URLEncoder.encode("myUserName", "UTF-8") + "&"
                + URLEncoder.encode("submit", "UTF-8") + "="
                + URLEncoder.encode("Submit", "UTF-8");


        URL requestUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) requestUrl
                .openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");

        OutputStreamWriter osw = new OutputStreamWriter(
                conn.getOutputStream());
        osw.write(data);
        osw.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        String in = "";
        sb = new StringBuffer();

        while ((in = br.readLine()) != null) {
            sb.append(in + "\n");
        }

        osw.close();
        br.close();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sb.toString();
}

This is the form I'm trying to send a request to (it's a form on the w3schools site, this being the site http://www.w3schools.com/html/html_forms.asp):

这是我想要发送的请求(它是w3schools网站上的一个表单,它是http://www.w3schools.com/html/html_forms.asp):

<form name="input0" target="_blank" action="html_form_action.asp" method="get">

Username: 

<input type="text" name="user" size="20" />

<input type="submit" value="Submit" />

</form>

Now because the Submit button doesn't have a name attribute, I can't send a proper HTTP Get/Post request to it (I know it's a get method in this case). What do I replace the String data with (what proper keys/values) so that it actually sends a request to this form?

现在,由于Submit按钮没有name属性,所以我不能发送适当的HTTP Get/Post请求(我知道这是一个Get方法)。我用什么来替换字符串数据(什么键/值),以便它实际向这个表单发送一个请求?

4 个解决方案

#1


1  

I am using HttpClient for generating http request

我正在使用HttpClient生成http请求。

HttpClient is open source apache project. you can get widely code. HttpClient version 4.1 is good set of Http api

HttpClient是开放源码的apache项目。你可以得到广泛的代码。HttpClient版本4.1是很好的Http api集。

HttpClient Learning Artical

HttpClient学习文章

#2


1  

You don't add the submit part to your data at all. This is just for the browser to know that "Submit" button triggers the action. Notice how the URL of the newly opened site looks: http://www.w3schools.com/html/html_form_action.asp?user=myUserName - no submit part here. So your data code should look like this:

您不会将提交部分添加到您的数据中。这只是为了让浏览器知道“提交”按钮触发了操作。注意新打开的站点的URL是什么样子:http://www.w3schools.com/html/html_form_action.asp?用户=myUserName -不提交。你的数据代码应该是这样的:

String data = URLEncoder.encode("user", "UTF-8") + "="
            + URLEncoder.encode("myUserName", "UTF-8"); // end here

#3


0  

//Making http get request

/ / http get请求

HttpClient httpClientDefault1 = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.your.targer.url.com/page.html");

//setup headers (Server understand request throw by some browser)

//设置头文件(服务器理解请求抛出浏览器)

httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
httpPost.setHeader("Accept", " text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-us,en;q=0.5");
httpPost.setHeader("Host", "ec2-23-20-44-83.compute-1.amazonaws.com");

httpPost.setHeader("Referer",resultUrl+resultUrlAsp);

httpPost.setHeader(“推荐人”,resultUrl + resultUrlAsp);

//Set parameters

/ /设置参数

ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("key",""));
nameValuePair.add(new BasicNameValuePair("txtenroll","095020693015"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

//Send request

/ /发送请求

HttpResponse httpRespnse = httpClientDefault1.execute(httpPost);

//Get Response body

/ /得到响应的身体

if(httpRespnse.getStatusLine().getStatusCode() != 200) {
    InputStream in =  httpRespnse.getEntity().getContent();
    byte b[] = new byte[1024] ;
    StringBuilder html = new StringBuilder("");
    while(in.read(b) != -1) {
        html.append((new String(b)).toString());
        b = new byte[1024];
    }
    System.out.println(html);
}

also you can get headers, http parameters, cookies, manage the session through the java code... :) :)

您还可以获得header、http参数、cookie,通过java代码管理会话……:):)

#4


0  

I have a ClientHttpRequest class that does all multiparts, files etc, with optional progress tracing and cancelation. It's been around for about 10 years. Pretty simple to use. Now there's a Scala version too. https://github.com/vpatryshev/ScalaKittens/blob/master/src/main/scala/scalakittens/ClientHttpRequest.scala

我有一个ClientHttpRequest类,它执行所有的多部分、文件等,可选择的进度跟踪和取消。它已经存在了大约10年。很简单的使用。现在还有一个Scala版本。https://github.com/vpatryshev/ScalaKittens/blob/master/src/main/scala/scalakittens/ClientHttpRequest.scala

http://myjavatools.com/

http://myjavatools.com/

#1


1  

I am using HttpClient for generating http request

我正在使用HttpClient生成http请求。

HttpClient is open source apache project. you can get widely code. HttpClient version 4.1 is good set of Http api

HttpClient是开放源码的apache项目。你可以得到广泛的代码。HttpClient版本4.1是很好的Http api集。

HttpClient Learning Artical

HttpClient学习文章

#2


1  

You don't add the submit part to your data at all. This is just for the browser to know that "Submit" button triggers the action. Notice how the URL of the newly opened site looks: http://www.w3schools.com/html/html_form_action.asp?user=myUserName - no submit part here. So your data code should look like this:

您不会将提交部分添加到您的数据中。这只是为了让浏览器知道“提交”按钮触发了操作。注意新打开的站点的URL是什么样子:http://www.w3schools.com/html/html_form_action.asp?用户=myUserName -不提交。你的数据代码应该是这样的:

String data = URLEncoder.encode("user", "UTF-8") + "="
            + URLEncoder.encode("myUserName", "UTF-8"); // end here

#3


0  

//Making http get request

/ / http get请求

HttpClient httpClientDefault1 = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.your.targer.url.com/page.html");

//setup headers (Server understand request throw by some browser)

//设置头文件(服务器理解请求抛出浏览器)

httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
httpPost.setHeader("Accept", " text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-us,en;q=0.5");
httpPost.setHeader("Host", "ec2-23-20-44-83.compute-1.amazonaws.com");

httpPost.setHeader("Referer",resultUrl+resultUrlAsp);

httpPost.setHeader(“推荐人”,resultUrl + resultUrlAsp);

//Set parameters

/ /设置参数

ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("key",""));
nameValuePair.add(new BasicNameValuePair("txtenroll","095020693015"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

//Send request

/ /发送请求

HttpResponse httpRespnse = httpClientDefault1.execute(httpPost);

//Get Response body

/ /得到响应的身体

if(httpRespnse.getStatusLine().getStatusCode() != 200) {
    InputStream in =  httpRespnse.getEntity().getContent();
    byte b[] = new byte[1024] ;
    StringBuilder html = new StringBuilder("");
    while(in.read(b) != -1) {
        html.append((new String(b)).toString());
        b = new byte[1024];
    }
    System.out.println(html);
}

also you can get headers, http parameters, cookies, manage the session through the java code... :) :)

您还可以获得header、http参数、cookie,通过java代码管理会话……:):)

#4


0  

I have a ClientHttpRequest class that does all multiparts, files etc, with optional progress tracing and cancelation. It's been around for about 10 years. Pretty simple to use. Now there's a Scala version too. https://github.com/vpatryshev/ScalaKittens/blob/master/src/main/scala/scalakittens/ClientHttpRequest.scala

我有一个ClientHttpRequest类,它执行所有的多部分、文件等,可选择的进度跟踪和取消。它已经存在了大约10年。很简单的使用。现在还有一个Scala版本。https://github.com/vpatryshev/ScalaKittens/blob/master/src/main/scala/scalakittens/ClientHttpRequest.scala

http://myjavatools.com/

http://myjavatools.com/