請求是從url獲取內容並正確處理內容(每次不同),然後將答案發回到同一個url。當我嘗試執行GET方法後的setRequestMethod(「POST」)時遇到「無法重置方法:已連接」。我的代碼如下Java - 如何爲GET和POST打開一個HttpURLConnection
public class MyClass {
/**
* @param args
*/
public MyClass() {};
public void process() {
String url = "http://www.somesite.com/";
String strPage = null;
int n = 0;
try{
URL urlObj = new URL(url);
HttpURLConnection urlConnection =
(HttpURLConnection)urlObj.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String strWhole = null;
while(null != (strPage = reader.readLine())){
strWhole += strPage;
}
//handle content here and calculate result
... ...
//send result below
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String urlParameters = "aa=bb&cc=dd&ee=ff";
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream in1 = urlConnection.getInputStream();
BufferedReader reader1 = new BufferedReader(new InputStreamReader(in));
while(null != (strPage = reader1.readLine())){
System.out.println(strPage);
}
reader1.close();
}
catch(Exception e){
String exception = e.getMessage();
System.out.println(exception);
if (reader != null) {
reader.close();
}
if (reader1 != null) {
reader1.close();
}
}
return;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyClass dp = new MyClass();
dp.process();
}
}
@Guiherme當我應該調用openConnection()? –
對不起,我修復了代碼。 –
@Guiherme謝謝,它不適合我。 kgeorgiy的解決方案是我所需要的:) –