=======================
=======================
=======================
public void post(String url) throws Exception {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.setDoOutput(true);
if (c instanceof HttpURLConnection) {
((HttpURLConnection) c).setRequestMethod("POST");
}
OutputStreamWriter out = new OutputStreamWriter(
c.getOutputStream());
// output your data here
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
c.getInputStream()));
String s = null;
while ((s = in .readLine()) != null) {
System.out.println(s);
} in .close();
}
=======================
=======================
=======================
출처: http://dimdol.blogspot.kr/2009/09/%EC%9E%90%EB%B0%94-http-post-%EC%9A%94%EC%B2%AD.html
자바 HTTP POST 요청
자바(1.4 이상)로 HTTP POST 요청을 하는 방법이다.
먼저 URLConnection 객체를 생성한다.
URL url = new URL("http://example.dimdol.com/example.jsp");
URLConnection con = url.openConnection();
URLConnection 객체 setRequestProperty 메소드로 HTTP 헤더 정보를 설정한다.
con.setRequestProperty("Accept-Language", "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3");
URLConnection 객체 setDoOutput 메소드로 POST 요청임을 설정한다.
con.setDoOutput(true);
요청 파라미터는 name=value 패턴으로 지정하고 두 개 이상은 &을 사용해서 연결한다.
String parameter = URLEncoder.encode("name", "UTF-8") + "=" URLEncoder.encode("dimdol", "UTF-8");
parameter += "&" + URLEncoder.encode("age", "UTF-8") + "=" URLEncoder.encode("35", "UTF-8");
HTTP 요청을 한다.
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(parameter);
wr.flush(); // 꼭 flush를 호출해야 한다.
응답 결과가 텍스트인 경우에는 다음과 같이 처리한다.
BufferedReader rd = null;
rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String line = null;
while ((line = rd.readLine()) != null) {
// 로직 처리
}
응답 결과가 XML인 경우에는 다음과 같이 처리한다.
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(con.getInputStream());
// 이하 document를 이용해서 로직 처리
응답 헤더는 다음과 같이 확인할 수 있다.
String cookie = con.getHeaderField("Set-Cookie");
전체를 try/finally로 묶고 finally 절에서 OutputStreamWriter과 BufferedReader를 close한다.
=======================
=======================
=======================
출처: http://www.developer.nokia.com/Community/Wiki/HTTP_Post_multipart_file_upload_in_Java_ME
This is a Swing application that demonstrates how to use the Jakarta HttpClient multipart POST method for uploading files.
/*
* $Header$
* $Revision$
* $Date$
* ====================================================================
*
* Copyright 2002-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import
org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
*
* This is a Swing application that demonstrates
* how to use the Jakarta HttpClient multipart POST method
* for uploading files
*
* @author Sean C. Sullivan
* @author Michael Becke
*
*/
public class MultipartFileUploadApp {
public static void main(String[] args) {
MultipartFileUploadFrame f = new MultipartFileUploadFrame();
f.setTitle("HTTP multipart file upload application");
f.pack();
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
f.setVisible(true);
}
public static class MultipartFileUploadFrame extends JFrame {
private File targetFile;
private JTextArea taTextResponse;
private DefaultComboBoxModel cmbURLModel;
public MultipartFileUploadFrame() {
String[] aURLs = {
"http://localhost:8080/httpclienttest/fileupload"
};
cmbURLModel = new DefaultComboBoxModel(aURLs);
final JComboBox cmbURL = new JComboBox(cmbURLModel);
cmbURL.setToolTipText("Enter a URL");
cmbURL.setEditable(true);
cmbURL.setSelectedIndex(0);
JLabel lblTargetFile = new JLabel("Selected file:");
final JTextField tfdTargetFile = new JTextField(30);
tfdTargetFile.setEditable(false);
final JCheckBox cbxExpectHeader = new JCheckBox(
"Use Expect header");
cbxExpectHeader.setSelected(false);
final JButton btnDoUpload = new JButton("Upload");
btnDoUpload.setEnabled(false);
final JButton btnSelectFile = new JButton("Select a file...");
btnSelectFile.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setDialogTitle("Choose a file...");
if (
chooser.showOpenDialog(
MultipartFileUploadFrame.this)
== JFileChooser.APPROVE_OPTION
) {
targetFile = chooser.getSelectedFile();
tfdTargetFile.setText(targetFile.toString());
btnDoUpload.setEnabled(true);
}
}
}
);
taTextResponse = new JTextArea(10, 40);
taTextResponse.setEditable(false);
final JLabel lblURL = new JLabel("URL:");
btnDoUpload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String targetURL = cmbURL.getSelectedItem().toString();
// add the URL to the combo model
// if it's not already there
if (!targetURL
.equals(
cmbURLModel.getElementAt(
cmbURL.getSelectedIndex()))) {
cmbURLModel.addElement(targetURL);
}
PostMethod filePost = new PostMethod(targetURL);
filePost.getParams().setBooleanParameter(
HttpMethodParams.USE_EXPECT_CONTINUE,
cbxExpectHeader.isSelected());
try {
appendMessage("Uploading " + targetFile.getName() +
" to " + targetURL);
Part[] parts = {
new FilePart(targetFile.getName(), targetFile)
};
filePost.setRequestEntity(
new MultipartRequestEntity(parts,
filePost.getParams())
);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().
getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
appendMessage(
"Upload complete, response=" +
filePost.getResponseBodyAsString()
);
} else {
appendMessage(
"Upload failed, response=" +
HttpStatus.getStatusText(status)
);
}
} catch (Exception ex) {
appendMessage("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
}
});
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.NONE;
c.gridheight = 1;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 5, 5, 0);
c.weightx = 1;
c.weighty = 1;
getContentPane().add(lblURL, c);
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 2;
c.gridx = 1;
c.insets = new Insets(5, 5, 5, 10);
getContentPane().add(cmbURL, c);
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(10, 5, 5, 0);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
getContentPane().add(lblTargetFile, c);
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5, 5, 5, 5);
c.gridwidth = 1;
c.gridx = 1;
getContentPane().add(tfdTargetFile, c);
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(5, 5, 5, 10);
c.gridwidth = 1;
c.gridx = 2;
getContentPane().add(btnSelectFile, c);
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(10, 10, 10, 10);
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 2;
getContentPane().add(cbxExpectHeader, c);
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(10, 10, 10, 10);
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 3;
getContentPane().add(btnDoUpload, c);
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(10, 10, 10, 10);
c.gridwidth = 3;
c.gridheight = 3;
c.weighty = 3;
c.gridx = 0;
c.gridy = 4;
getContentPane().add(new JScrollPane(taTextResponse), c);
}
private void appendMessage(String m) {
taTextResponse.append(m + "\n");
}
}
}
=======================
=======================
=======================
출처: http://stackoverflow.com/questions/1599018/java-applet-to-upload-a-file
i am looking for a Java applet to read a file from client machine and creat a POST request for PHP server uploading.
PHP script on server should receive the file as normal file upload in FORM submit. I am using the following code. The file contents are passed to PHP script but they are not correctly converted to an image.
//uploadURL will be a url of PHP script like
// http://www.example.com/uploadfile.php
URL url = new URL(uploadURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
InputStream is = new FileInputStream("C://img.jpg");
OutputStream os = con.getOutputStream();
byte[] b1 = new byte[10000000];
int n;
while ((n = is.read(b1)) != -1) {
os.write("hello", 0, 5);
test += b1;
}
con.connect();
2 Answers
active oldest votes
up vote 6 down vote accepted
Here's some code that might help you .. it's from one of my old projects with a bunch of unrelated stuff removed, take it for what it's worth. Basically, I think the code in your question is missing some parts that the HTTP protocol requires. Good luck!
public class UploaderExample
{
private static final String Boundary = "--7d021a37605f0";
public void upload(URL url, List<File> files) throws Exception
{
HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection();
theUrlConnection.setDoOutput(true);
theUrlConnection.setDoInput(true);
theUrlConnection.setUseCaches(false);
theUrlConnection.setChunkedStreamingMode(1024);
theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ Boundary);
DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream());
for (int i = 0; i < files.size(); i++)
{
File f = files.get(i);
String str = "--" + Boundary + "\r\n"
+ "Content-Disposition: form-data;name=\"file" + i + "\"; filename=\"" + f.getName() + "\"\r\n"
+ "Content-Type: image/png\r\n"
+ "\r\n";
httpOut.write(str.getBytes());
FileInputStream uploadFileReader = new FileInputStream(f);
int numBytesToRead = 1024;
int availableBytesToRead;
while ((availableBytesToRead = uploadFileReader.available()) > 0)
{
byte[] bufferBytesRead;
bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead]
: new byte[availableBytesToRead];
uploadFileReader.read(bufferBytesRead);
httpOut.write(bufferBytesRead);
httpOut.flush();
}
httpOut.write(("--" + Boundary + "--\r\n").getBytes());
}
httpOut.write(("--" + Boundary + "--\r\n").getBytes());
httpOut.flush();
httpOut.close();
// read & parse the response
InputStream is = theUrlConnection.getInputStream();
StringBuilder response = new StringBuilder();
byte[] respBuffer = new byte[4096];
while (is.read(respBuffer) >= 0)
{
response.append(new String(respBuffer).trim());
}
is.close();
System.out.println(response.toString());
}
public static void main(String[] args) throws Exception
{
List<File> list = new ArrayList<File>();
list.add(new File("C:\\square.png"));
list.add(new File("C:\\narrow.png"));
UploaderExample uploader = new UploaderExample();
uploader.upload(new URL("http://systemout.com/upload.php"), list);
}
}
관련링크:
http://www.velocityreviews.com/forums/t151666-posting-through-http-post-in-applet.html
http://www.albumbang.com/board/board_view.jsp?board_name=free&no=292
http://www.developer.nokia.com/Community/Wiki/HTTP_Post_multipart_file_upload_in_Java_ME
http://stackoverflow.com/questions/6917105/java-http-client-to-upload-file-over-post
http://stackoverflow.com/questions/9692166/http-post-in-java-with-file-upload
=======================
=======================
=======================
'JAVA' 카테고리의 다른 글
[Java] Queue 의 종류와 용법, 자바 병렬 프로그래밍 - 구성 단위 (0) | 2020.09.20 |
---|---|
자바 이미지생성, 이미지 버퍼, 이미지 메모리 생성 관련 (0) | 2020.09.18 |
자바개발 FTP 관련 (0) | 2020.09.18 |
자바 파일스트림 쓰기 (0) | 2020.09.18 |
이클립스 java Class Path 관련 (0) | 2020.09.18 |