티스토리 뷰

private String multipartRequest(ArrayList<String> datas){
try{
URL Url = new URL(url);
Log.d("httputils","서버로 MultiPart 요청 : "+url);
con = (HttpURLConnection) Url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
con.setDefaultUseCaches(false);
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
setCookieHeader();
//사용자가 로그인해서 세션 쿠키를 서버로부터 발급받은적 있다면 그 다음 요청 헤더 부터는 그 세션 쿠키를 포함해서 전송해야 함.
OutputStream os = con.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
for(int i=0; i<datas.size(); i++) {
dos.writeBytes("--" + boundary + CRLF);
File file = new File(datas.get(i));
if(!file.exists())
Log.d("httputils",datas.get(i)+"에 해당하는 파일이 존재 하지 않습니다.");
dos.writeBytes("Content-Disposition: form-data; name=\"image"+(i+1)+"\";filename=\"" + file.getName() + "\"" + CRLF);
dos.writeBytes(CRLF);
FileInputStream fis = new FileInputStream(datas.get(i)); //datas.get(i) -> 이미지 파일의 절대경로

int buffersize;
while( (buffersize = Math.min(fis.available(),1024)) > 0) { //운영체제에서 1024바이트 단위로 데이터를 읽기 때문
byte[] buffer = new byte[buffersize];
fis.read(buffer,0,buffersize);
dos.write(buffer);
}
dos.writeBytes(CRLF);
}
dos.writeBytes("--"+boundary+"--"+CRLF);
dos.flush();
dos.close();

/*
POST /files HTTP/1.1
Host: localhost
Cache-Control: no-cache
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="sav.txt"
Content-Type: text/plain

나는 데이터 입니다.
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="otherFile.txt"
Content-Type: text/plain

나는 다른 데이터입니다.
------WebKitFormBoundary7MA4YWxkTrZu0gW--
*/
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { //이때 요청이 보내짐.
Log.d("LOG", "HTTP_OK를 받지 못했습니다.");
return null;
}

// int bytesAvailable = mFileInputStream.available();
// int maxBufferSize = 1024;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
//
// byte[] buffer = new byte[bufferSize];
// int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
//
// Log.d("Test", "image byte is " + bytesRead);
//
// // read image
// while (bytesRead > 0) {
// dos.write(buffer, 0, bufferSize);
// bytesAvailable = mFileInputStream.available();
// bufferSize = Math.min(bytesAvailable, maxBufferSize);
// bytesRead = mFileInputStream.read(buffer, 0, bufferSize);
// }
//
// dos.writeBytes(lineEnd);
// dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

String line;
String page = "";
while ((line = reader.readLine()) != null){
page += line;
}
getCookieHeader();
return page;
} catch (MalformedURLException e) { // for URL.
e.printStackTrace();
} catch (IOException e) { // for openConnection().
e.printStackTrace();
} finally {
if (con != null)
con.disconnect();
}

return null;

}

매개변수 ArrayList<String> datas는 어디로 부터 넘어오는걸까?


WriteFragmentRecyclerAdapter(글쓰기창 어댑터)에서 텍스트만 따로 취합한다음에 WriteFragment로 넘긴다.

public ArrayList<WriteFragComponent> getDatas() {
for(WriteFragComponent c : datas){
if(c.getType() == STATE_TEXT)
c.setString(mTextHolder.editText.getText().toString());
}
return datas;
}


WriteFragment(글쓰기창)의 getDatas()에서는 타이틀에 입력된 텍스트까지 ArrayList<WriteFragComponent>에 추가

public ArrayList<WriteFragComponent> getDatas(){ // 글쓰기창에 입력한 값들을 서버로 multipart 전송하기 위해서 취합하는 함수
WriteFragComponent comp = new WriteFragComponent(WriteFragmentRecyclerAdapter.STATE_TITLE,-1,mTitle.getText().toString());
mRecyclerAdapter.getDatas().add(comp);
return mRecyclerAdapter.getDatas();
}

그리고 나서, QnAActivity에서 (글쓰기 & 질문답변창) 플로팅 액션 버튼 클릭시 HttpUtils의 멀티파트 요청 메소드 실행한다.

mFab2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ArrayList<WriteFragComponent> datas = mWriteFragment.getDatas();
HttpUtils.getInstance(HttpUtils.MULTIPART,null, Constant.TestURL,getApplicationContext(),datas)
.execute();
}
});


댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함