ตัวอย่างที่ผมเขียนเรียกปกติ
String vXMLStr = request.getParameter("data");
OutputStream vOs = null;
OutputStreamWriter vOsw = null;
URL vUrl = new URL(request.getParameter("url"));
HttpURLConnection vHttpConn = (HttpURLConnection) vUrl.openConnection();
vHttpConn.setUseCaches(false);
vHttpConn.setRequestMethod("POST");
vHttpConn.setRequestProperty("Content-Type", "application/x-www-urlencoded");
vHttpConn.setRequestProperty("Content-Length", Integer.toString(vXMLStr.length()));
vHttpConn.setDoInput(true);
vHttpConn.setDoOutput(true);
vHttpConn.connect();
vOs = vHttpConn.getOutputStream();
vOsw = new OutputStreamWriter(vOs);
vOsw.write(vXMLStr);
vOsw.flush();
vOsw.close();
vOsw = null;
vOs = null;
// get response
InputStream vIs = null;
vIs = vHttpConn.getInputStream();
DataInputStream din = new DataInputStream(vIs);
StringBuffer buffer = new StringBuffer();
String b = "";
while(din.available() > 0) {
buffer.append(b);
}
vIs.close();
System.out.println("Result : " + buffer.toString());
OutputStream vOs = null;
OutputStreamWriter vOsw = null;
URL vUrl = new URL(request.getParameter("url"));
HttpURLConnection vHttpConn = (HttpURLConnection) vUrl.openConnection();
vHttpConn.setUseCaches(false);
vHttpConn.setRequestMethod("POST");
vHttpConn.setRequestProperty("Content-Type", "application/x-www-urlencoded");
vHttpConn.setRequestProperty("Content-Length", Integer.toString(vXMLStr.length()));
vHttpConn.setDoInput(true);
vHttpConn.setDoOutput(true);
vHttpConn.connect();
vOs = vHttpConn.getOutputStream();
vOsw = new OutputStreamWriter(vOs);
vOsw.write(vXMLStr);
vOsw.flush();
vOsw.close();
vOsw = null;
vOs = null;
// get response
InputStream vIs = null;
vIs = vHttpConn.getInputStream();
DataInputStream din = new DataInputStream(vIs);
StringBuffer buffer = new StringBuffer();
String b = "";
while(din.available() > 0) {
buffer.append(b);
}
vIs.close();
System.out.println("Result : " + buffer.toString());
ซึ่งดูจากตัวอย่างจะเห็นว่าผมใช้ din.available() > 0 ซึ่งบางทีไปเรียกแล้วจะรับค่าไม่ได้ จำเป็นต้องเปลี่ยนเป็นวิธีอื่น เช่น ที่ผมรับไม่ได้ผมแก้เป็น (b = din.readLine()) != null ตัวนี้แทนก็จะทำงานได้ครับ สามารถรับค่าได้ครับ
0 comments:
แสดงความคิดเห็น