자바 시 뮬 레이 션 병행 접근

3778 단어
클래스: NetUtils. java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Properties;

public class NetUtils
{

public static final String CHARACTER_ENCODING = "UTF-8";
public static final String PATH_SIGN = "/";
public static final String METHOD_POST = "POST";
public static final String METHOD_GET = "GET";
public static final String CONTENT_TYPE = "Content-Type";

/**
* POST ,
*
* @param urlString
* @param requestData
* @return
* @throws Exception
*/
public static byte[] requestPost(String urlString, byte[] requestData)
throws Exception
{
Properties requestProperties = new Properties();
requestProperties.setProperty(CONTENT_TYPE,
"application/octet-stream; charset=utf-8");

return requestPost(urlString, requestData, requestProperties);
}

/**
* POST ,
*
* @param urlString
* @param requestData
* @param requestProperties
* @return
* @throws Exception
*/
public static byte[] requestPost(String urlString, byte[] requestData,
Properties requestProperties) throws Exception
{
byte[] responseData = null;
HttpURLConnection con = null;

try {
URL url = new URL(urlString);
con = (HttpURLConnection) url.openConnection();
//
if ((requestProperties != null) && (requestProperties.size() > 0))
{
for (Map.Entry entry : requestProperties.entrySet())
{
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
con.setRequestProperty(key, value);
}
}

con.setRequestMethod(METHOD_POST); // POST

con.setDoInput(true); //
con.setDoOutput(true); //

// , 。
if (requestData != null)
{
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
dos.write(requestData);
dos.flush();
dos.close();
}

int length = con.getContentLength();
// -1, 。
if (length != -1)
{
DataInputStream dis = new DataInputStream(con.getInputStream());
responseData = new byte[length];
dis.readFully(responseData);
dis.close();
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (con != null)
{
con.disconnect();
con = null;
}
}
return responseData;
}

}

좋은 웹페이지 즐겨찾기