请求是从URL获取内容并正确处理内容(每次都不同),然后将答案发回相同的URL。我在GET方法执行后尝试setRequestMethod(“POST”)时遇到“无法重置方法:已连接”。我的代码如下
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();
}
}
答案 0 :(得分:1)
重用HttpURLConnection
实例是不可能的。但是documentation说,在幕后,Java会为你重用连接:
JDK支持HTTP / 1.1和HTTP / 1.0持久连接。
当应用程序完成读取响应正文或应用程序在
close()
返回的InputStream
上调用URLConnection.getInputStream()
时,JDK的HTTP协议处理程序将尝试清理连接,如果成功,则将连接放入连接缓存中,以供将来的HTTP请求重用。对HTTP keep-Alive的支持是透明的。
因此,无需手动重用连接。
答案 1 :(得分:0)
您必须先设置所有参数。这是我在我的应用程序中使用的代码:
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("app_token", "my token"); // optional header you can set with your own data
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
InputStream is = connection.getInputStream();
byte[] b = readWithoutSize(is);
is.close();
readWithoutSize是:
public static byte[] readWithoutSize(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
byte[] buf = new byte[512];
int leu;
while ((leu = is.read(buf)) != -1)
baos.write(buf,0,leu);
return baos.toByteArray();
}