请求是从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的解决方案是我所需要的:) –