Javaは、GETリクエストをサーバーに送信します
コードコピーは次のとおりです。
パッケージcom.hongyuan.test;
java.io.bufferedreaderをインポートします。
java.io.ioexceptionをインポートします。
java.io.inputStreamReaderをインポートします。
java.io.printwriterをインポートします。
java.net.httpurlconnectionをインポートします。
java.net.urlをインポートします。
パブリッククラスhttpclient {
// getリクエストを送信します
public static string get(string path)スロー例外{
httpurlconnection httpconn = null;
bufferedreader in = null;
試す {
url url = new url(path);
httpconn =(httpurlconnection)url.openconnection();
//応答を読みます
if(httpconn.getResponseCode()== httpurlconnection.http_ok){
stringbuffer content = new StringBuffer();
string tempsstr = "";
in = new BufferedReader(new inputStreamReader(httpconn.getInputStream()));
while((tempstr = in.readline())!= null){
content.append(tempstr);
}
return content.toString();
}それ以外{
新しい例外をスローします(「リクエストに問題があります!」);
}
} catch(ioException e){
e.printstacktrace();
} ついに{
in.close();
httpconn.disconnect();
}
nullを返します。
}
// get requestを送信します、パラメーターフォームkey1 = value1&key2 = value2 ...
public static string post(string path、string params)スロー例外{
httpurlconnection httpconn = null;
bufferedreader in = null;
printwriter out = null;
試す {
url url = new url(path);
httpconn =(httpurlconnection)url.openconnection();
httpconn.setRequestMethod( "post");
httpconn.setDoinput(true);
httpconn.setDoOutput(true);
// post Request Parametersを送信します
out = new PrintWriter(httpconn.getOutputStream());
out.println(params);
out.flush();
//応答を読みます
if(httpconn.getResponseCode()== httpurlconnection.http_ok){
stringbuffer content = new StringBuffer();
string tempsstr = "";
in = new BufferedReader(new inputStreamReader(httpconn.getInputStream()));
while((tempstr = in.readline())!= null){
content.append(tempstr);
}
return content.toString();
}それ以外{
新しい例外をスローします(「リクエストに問題があります!」);
}
} catch(ioException e){
e.printstacktrace();
} ついに{
in.close();
out.close();
httpconn.disconnect();
}
nullを返します。
}
public static void main(string [] args)スロー例外{
// string resmessage = httpclient.get( "http:// localhost:3000/hello?hello = hello get");
string resmessage = httpclient.post( "http:// localhost:3000/hello"、 "hello = hello post");
System.out.println(Resmessage);
}
}