URLConnection 发送get和post请求

package test.com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class testNg {


public String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
     try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            Map<String, List<String>> map = connection.getHeaderFields();


for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
//接收核心返回过来的数据 xml  需要解析
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {


e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}


public String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
                    //接收核心返回过来的数据 xml  需要解析
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {


e.printStackTrace();
}finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}


/**
* @param args
*/
public static void main(String[] args) {
testNg t=new testNg();

String sr = t.sendPost("http://api.xianmetro.strans-city.com:80/api/v1/app/login","{\"appId\":\"xianmetro\",\"mobile\":\"13986027185\",\"password\":\"a1234567\",\"alipayUserId\":\"20881111111\",\"deviceId\":\"xxxxxx\",\"clientType\":1,\"pushToken\":\"push_token_1111111\"}");
System.out.println(sr);
// String sr1 = httpclient.sendGet("https://mapi.alipay.com/gateway.do",
// "service=notify_verify&partner=2088701301711436&notify_id=d47c9358d0252cf0810942e324542deijq");
// System.out.println(sr1);
}


**
* 普通POST请求
*/
@SuppressWarnings("deprecation")
public static String HttpPost(String url, String body)  throws Exception{
    String jsonString = "";
    HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
    client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间
    client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
    PostMethod method = new PostMethod(url);
    method.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    method.setRequestBody(body);
    try {
        client.executeMethod(method);
        jsonString = method.getResponseBodyAsString();
    } catch (Exception e) {
        jsonString = "error";
        logger.error("HTTP请求路径时错误:" + url, e.getMessage());
        throw e; // 异常外抛
    } finally {
        if (null != method)
            method.releaseConnection();
    }
    return jsonString;
}
/**
* JSON的POST请求
*/

@SuppressWarnings("deprecation")

public static String HttpPostJSON(String url, JSONObject body)  throws Exception{

String jsonString = "";
HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间
client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
client.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    PostMethod method = new PostMethod(url);
    method.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    method.setRequestBody(body.toString());
    try {
        client.executeMethod(method);
        jsonString = method.getResponseBodyAsString();
    } catch (Exception e) {
        jsonString = "error";
        logger.error("HTTP请求路径时错误:" + url, e.getMessage());
        throw e; // 异常外抛
    } finally {
        if (null != method)
            method.releaseConnection();
    }
    return jsonString;
}
/**
* XML的POST请求
*/
@SuppressWarnings("deprecation")
public static String HttpPostXml(String url, String xmlBody)  throws Exception{
String result = "";
HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
 client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); //通过网络与服务器建立连接的超时时间
client.getHttpConnectionManager().getParams().setSoTimeout(60000); //Socket读数据的超时时间,即从服务器获取响应数据需要等待的时间
PostMethod method = new PostMethod(url);
 method.setRequestHeader("Content-Type", "application/xml");
if(null != xmlBody){
 method.setRequestBody(xmlBody);
 }
try {
   client.executeMethod(method);
  result = method.getResponseBodyAsString();
 } catch (Exception e) {
  result = "error";
   logger.error("HTTP请求路径时错误:" + url, e.getMessage());
  throw e; // 异常外抛
} finally {
 if (null != method)
  method.releaseConnection();
}
  return result;



















}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 发送Post请求是一种用于向服务器发送数据的HTTP请求方法。它常用于提交表单数据、上传文件或者更新服务器上的资源。 要发送Post请求,我们需要以下步骤: 1. 创建一个URL对象,指定请求的URL地址。 2. 创建一个URLConnection对象,用于建立和服务器的连接。 3. 设置URLConnection请求方法为Post,并且设置URLConnection可进行输入和输出。 4. 构造请求参数,并将其写入URLConnection的输出流中。 5. 获取服务器响应,读取URLConnection的输入流。 以下是一个示例代码: ```java import java.io.*; import java.net.*; public class PostRequestExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com"); // 创建URLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为Post,并允许输入输出 connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); // 构造请求参数 String param = "username=test&password=123456"; byte[] requestData = param.getBytes(); // 写入请求参数 OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestData); outputStream.flush(); outputStream.close(); // 获取服务器响应 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出服务器响应 System.out.println(response.toString()); // 关闭连接 connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上是使用Java代码发送Post请求的示例。通过构造合适的请求参数,并将其写入到输出流中,我们可以向服务器发送Post请求,并获取服务器的响应。 ### 回答2: 发送POST请求是一种常见的网络请求方式,它可以向服务器提交数据,并获取服务器返回的响应结果。在发送POST请求时,需遵循以下步骤: 1. 创建一个URL对象,该对象包含请求的URL地址。 2. 打开一个连接到服务器的连接,可以通过URLConnection类的openConnection()方法创建,也可以使用HttpClient等其他网络请求库。 3. 设置请求的方法为POST请求,可以通过URLConnection类的setRequestMethod()方法将请求方法设置为POST。 4. 设置请求头信息,使用setRequestProperty()方法设置请求的头部字段,如Content-Type、Authorization等。 5. 获取输出流,将需要发送的数据写入输出流中,可以通过调用URLConnection类的getOutputStream()方法获取输出流。 6. 发送数据,将写入输出流中的数据发送给服务器。 7. 获取服务器响应,可以通过调用URLConnection类的getInputStream()方法获取响应的输入流。 8. 读取响应数据,从输入流中读取服务器返回的响应数据。 9. 关闭连接和输入输出流,使用close()方法关闭打开的连接以及相关的输入输出流。 总结来说,发送POST请求的流程是创建URL对象,打开连接,设置请求方法和头部信息,获取输出流并写入需要发送的数据,发送数据,获取服务器的响应输入流,读取响应数据,关闭连接和输入输出流。这样就可以成功地发送POST请求并获取到服务器的响应结果。 ### 回答3: 发送POST请求是一种在网络通信中常见的方法。通过POST请求,可以向服务器发送数据,并且能够保留请求的主体部分,这使得POST请求比GET请求更适合发送大量数据或敏感信息。 要发送POST请求,首先需要确定请求的目标URL,即要发送数据的服务器地址。然后,需要创建一个HTTP连接,并指定使用POST方法进行通信。接下来,需要设置请求头,包括Content-Type字段,用于指定请求主体的数据类型。 发送POST请求时,需要将要发送的数据组织成适当的格式,并将其放置在请求主体中。常见的数据格式包括JSON、XML或表单数据。如果是表单数据,可以使用表单编码格式,将数据以key-value的形式进行传输。 最后,使用HTTP连接发送POST请求,并等待服务器的响应。服务器接收到POST请求后,会解析请求主体中的数据,并根据业务逻辑进行处理。服务器处理完请求后,会返回响应数据,可以根据响应的状态码和数据来判断请求是否成功。 总结来说,发送POST请求需要确定目标URL、创建HTTP连接、设置请求头、组织数据格式并放置在请求主体中,然后发送请求并等待响应。这样,我们就可以通过POST请求与服务器进行数据交互。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值