다음 두 가지 방법은 Java를 사용하여 URL 요청을 보내고 서버에서 반환 한 값을 얻습니다.
첫 번째 방법 :
코드 사본은 다음과 같습니다.
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.httpclient;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httppost;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.params.coreconnectionpnames;
import org.apache.http.util.entityutils;
PublicStaticStringsEndurlRequest (StringUrlstr, StringParam1, StringParam2) ThrowSexception {
stringtempstr = null;
httpclienthttpclient = newdefaulthttpclient ();
propertiesProperties = newProperties ();
httpentityentity = null;
StringXmlContent = "";
노력하다
{
// 타임 아웃 시간을 설정합니다
httpclient.getParams (). setIntParameter (coreConnectionpnames.connection_timeout, 20000);
httpclient.getparams (). setParameter (coreconnectionpnames.so_timeout, 20000);
// 통과 해야하는 매개 변수의 캡슐화
List <NamesValuePair> nvps = newArrayList <NamesValuePair> ();
nvps.add (newbasicnamevaluepair ( "mainmemocode", strmainmemocode));
nvps.add (newbasicnamevaluepair ( "recordpassword", strrecordpassword));
// 클라이언트 요청 메소드 유형
httpposthttppost = newhttppost (urlstr);
httppost.
httpresponsponsponse = httpclient.execute (httppost);
// 서버가 http로 반환하는 컨텐츠 유형의 값을 얻습니다.
tempstr = response.getheaders ( "content-type") [0] .getValue (). toString ();
// 서버에서 반환 한 페이지 값을 가져옵니다.
엔티티 = response.getEntity ();
xmlcontent = entityutils.tostring (entity);
stringstrmessage = null;
System.out.println (xmlcontent);
System.out.println (response.getheaders ( "content-type") [0] .getValue (). toString ());
httppost.abort ();
}
CATCH (SocketTimeOutExceptione)
{
}
CATCH (ExceptionEx)
{
ex.printstacktrace ();
}
마지막으로{
httpclient.getConnectionManager (). shutdown ();
}
두 번째 방법 :
코드 사본은 다음과 같습니다.
PublicStaticStringsEndurlRequest (StringUrlstr, StringParam1, StringParam2) ThrowSexception {
httpurlconnectionurl_con = null;
노력하다{
urlurl = newurl (urlstr);
StringBufferBankXmlBuffer = NewStringBuffer ();
// URL 연결 생성, 데이터에 제출 한 후 반환 결과를 얻습니다.
httpurlConnectionConnection = (httpurlConnection) url.openConnection ();
Connection.setRequestMethod ( "post");
Connection.setDoOutput (true);
Connection.setRequestProperty ( "사용자 에이전트", "DirectClient");
PrintWriterOut = NewPrintwriter (NewOutputStreamWriter (Connection.GetOutputStream (), "GBK");
out.println (param);
out.close ();
BufferedReaderIn = NewbufferedReader (NewInputStreamReader (Connection
.getInputStream (), "gbk");
StringInputline;
while ((inputline = in.readline ())! = null) {
bankxmlbuffer.append (inputline);
}
넣다();
tempstr = bankxmlbuffer.toString ();
}
캐치 (예외)
{
System.out.println ( "get request!" +e)를 보낼 때 예외가 발생했습니다.
e.printstacktrace ();
} 마지막으로{
if (url_con! = null)
url_con.disconnect ();
}
returnmpest;
}