Java活用生活

ログイン

オンライン状況

オンラインユーザー1人
ログインユーザー0人
登録ユーザー2人

カウンタ

COUNTER335459

日誌

MyDoc(備忘録) >> 記事詳細
2023/08/23

文字列と画像をpost送信(再掲・補足追加)

固定リンク | by:aramaki
文字列と画像をpost送信(再掲・捕捉追加)
----------------------------------------------------------------
以前、掲載した「PostMultipart.java」の補足追加版です
。このクラスの送信した文字列と画像は、サーバー側PHP(UTF-8)で処理します。
そのため、レスポンス文字列の先頭にBOMがあるため、そのため、BOM判定して、
BOMを除去しました。なお、connect()についても補足しています。

--------------------------------------------------------------------------------------------------
package multi.part.post;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class PostMultipart {
/** 改行コード */
private static final String LINE_FEED = "\r\n";
/** コンテンツ境界線 */
private String boundary;
/** HTTP接続インターフェイス */
private HttpURLConnection httpConnection;
/** 文字コード */
private String charset;
/** リクエスト出力ストリーム */
private OutputStream outputStream;
/** データをテキスト出力ストリームに出力する */
private PrintWriter writer;

// コンストラクタ
public PostMultipart(String requestUrl, String charset) throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestUrl);
httpConnection = (HttpURLConnection) url.openConnection();

// 2023 08/20 追加
httpConnection.setRequestMethod("POST"); // これがなくても動作する

httpConnection.setUseCaches(false);
// リクエストボディー送信を許可
httpConnection.setDoOutput(true);
// レスポンスボディー受信許可
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

init();
}
// 初期処理
private void init() throws IOException{

// 2023 08/20 追加
//httpConnection.connect(); // これがなくても動作する
// connect()捕捉
// 接続されていない URLConnection に対して接続が必要な操作を行うと、 自動的に接続されます。
// 参照>http://fujimura2.fiw-web.net/java/appendix/net/URLConnection/index.html

outputStream = httpConnection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}

/**
* フォームフィールド追加
*
* @param name
*            パラメータ名
* @param value
*            パラメータ値
*/
public void addField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}

// 送信するファイルの追加
public void addFile(String name, File uploadFile) throws IOException {
FileInputStream inputStream = null;
try {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();

// 指定ファイルと取り込み、出力ストリームに出力する
inputStream = new FileInputStream(uploadFile);

// 読込みバッファ
byte[] buffer = new byte[4096];
int byteRead = -1;
while ((byteRead = inputStream.read(buffer)) != -1) {
// データをサーバーリクエストへ書き込み
outputStream.write(buffer, 0, byteRead);
}
outputStream.flush();
writer.append(LINE_FEED);
writer.flush();
} finally {
if (inputStream != null) {
inputStream.close();
}
//以下をコメントインするとhttpConnectionを切断するのでサーバーにデータが送信されない
// if (outputStream != null) {
// outputStream.close();
// }
}
}
//

/**
* ヘッダー追加
*
* @param name
*            ヘッダー名
* @param value
*            ヘッダー値
*/
public void addHeader(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();

}

/**
* POST 送信処理
*
* @return
* @throws IOException
*/
public List<String> post() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();

boolean isBomFlg=false;
// サーバーステイタスコードチェック
int status = httpConnection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line = null;
//int cnt=0;
while ((line = reader.readLine()) != null) {
if(isBomFlg==false){
if(isBomLine(line)){
isBomFlg=true;
// BOMの先頭行はスキップ
continue;
}
}
response.add(line);
}
reader.close();
httpConnection.disconnect();
} else {
throw new IOException("Send Fail: " + status);
}
return response;
}

// サーバー側から(PHP)レスポンスで返される文字列にBOMがあるか判定する。
    private boolean isBomLine(String line){

        if(line==null || line.trim().length()==0){
            return false;
        }
        // レスポンス文字列をバイト配列に変換する。
        byte[] lineToByte=line.getBytes();
        int size=lineToByte.length;

        // 変換したバイト配列の要素数でない場合、BOM文字の数値ではないので、falseを返す。
        if(size!=3){
            return false;
        }
        // byte値をint型に変換した各要素を代入するへ配列変数
        int[] charCode=new int[3];
        for(int i=0;i<size;i++){
            charCode[i]=new Byte(lineToByte[i]).intValue();
        }
        if((-17==charCode[0]) && (-69 == charCode[1]) && (-65 == charCode[2])) {
            return true;
        }

        return false;

    }




}

11:50 | 投票する | 投票数(0) | コメント(0)
Copyright © Java活用生活 All Rights Reserved .