Java는 요청을 서버로 보내고 게시합니다
코드 사본은 다음과 같습니다.
패키지 com.hongyuan.test;
import java.io.bufferedReader;
import java.io.ioexception;
import java.io.inputStreamReader;
import java.io.printwriter;
import java.net.httpurlConnection;
import java.net.url;
공개 클래스 httpclient {
// GET 요청을 보냅니다
공용 정적 문자열 get (String Path)는 예외를 던지려고 {
httpurlconnection httpconn = null;
버퍼드 리더 in = null;
노력하다 {
URL URL = 새 URL (PATH);
httpconn = (httpurlConnection) url.openConnection ();
// 응답을 읽습니다
if (httpconn.getResponseCode () == httpurlConnection.http_ok) {
StringBuffer content = new StringBuffer ();
문자열 tempstr = "";
in = new bufferedReader (new inputStreamReader (httpconn.getInputStream ()));
while ((tempstr = in.readline ())! = null) {
content.append (tempstr);
}
return content.toString ();
}또 다른{
새로운 예외를 던지십시오 ( "요청에 문제가 있습니다!");
}
} catch (ioexception e) {
e.printstacktrace ();
} 마지막으로{
넣다();
httpconn.disconnect ();
}
널 리턴;
}
// get request, 매개 변수 양식 key1 = value1 & key2 = value2를 보내십시오.
public static string post (문자열 경로, 문자열 매개 변수) 예외 {
httpurlconnection httpconn = null;
버퍼드 리더 in = null;
printwriter out = null;
노력하다 {
URL URL = 새 URL (PATH);
httpconn = (httpurlConnection) url.openConnection ();
httpconn.setRequestMethod ( "post");
httpconn.setdoinput (true);
httpconn.setdooutput (true);
// 게시물 요청 매개 변수를 보냅니다
out = new printwriter (httpconn.getoutPutStream ());
out.println (params);
out.flush ();
// 응답을 읽습니다
if (httpconn.getResponseCode () == httpurlConnection.http_ok) {
StringBuffer content = new StringBuffer ();
문자열 tempstr = "";
in = new bufferedReader (new inputStreamReader (httpconn.getInputStream ()));
while ((tempstr = in.readline ())! = null) {
content.append (tempstr);
}
return content.toString ();
}또 다른{
새로운 예외를 던지십시오 ( "요청에 문제가 있습니다!");
}
} catch (ioexception e) {
e.printstacktrace ();
} 마지막으로{
넣다();
out.close ();
httpconn.disconnect ();
}
널 리턴;
}
public static void main (string [] args)은 예외 {
// String resmessage = httpclient.get ( "http : // localhost : 3000/hello? hello = hello get");
문자열 resmessage = httpclient.post ( "http : // localhost : 3000/hello", "hello = hello post");
System.out.println (Resmessage);
}
}