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;



















}

猜你喜欢

转载自blog.csdn.net/jessecary/article/details/79666352